充分利用属性来确定正确的调用方法
我有两个使用相同操作名称调用的操作方法,但是,根据实际参数类型,应调用哪个方法。这会导致歧义。我创建了一个属性来确定参数是否是 Guid 并且是适当的方法。
[RequiredGuidParameter(ParameterName = "title")]
[ActionName("Title")]
public ActionResult Item_ById(Guid id)
{ ... }
[ActionName("Title")]
public ActionResult Item_ByName(string id)
{ ... }
该属性如下所示:
public string ParameterName = string.Empty;
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
object parameter = null;
try
{
parameter = controllerContext.RouteData.GetRequiredString(ParameterName) as object;
if (parameter != null)
{
Guid guid;
return Guid.TryParse((string)parameter, out guid);
}
}
catch { }
parameter = controllerContext.RequestContext.HttpContext.Request[ParameterName] as object;
if (parameter != null)
{
Guid guid;
return Guid.TryParse((string)parameter, out guid);
}
return false;
}
最终目标是,如果参数是 Guid,则运行此方法,否则继续,在这种情况下,它会找到下一个。有没有更好的方法,不涉及创建额外的路线?或者也许有更好的方法?
I have two action methods that are called using the same action name, however, depending on the actual parameter type depends which method should be called. This causes ambiguity. I created an attribute that determines if the parameter is a Guid and is the appropriate method.
[RequiredGuidParameter(ParameterName = "title")]
[ActionName("Title")]
public ActionResult Item_ById(Guid id)
{ ... }
[ActionName("Title")]
public ActionResult Item_ByName(string id)
{ ... }
The attribute looks like this:
public string ParameterName = string.Empty;
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
object parameter = null;
try
{
parameter = controllerContext.RouteData.GetRequiredString(ParameterName) as object;
if (parameter != null)
{
Guid guid;
return Guid.TryParse((string)parameter, out guid);
}
}
catch { }
parameter = controllerContext.RequestContext.HttpContext.Request[ParameterName] as object;
if (parameter != null)
{
Guid guid;
return Guid.TryParse((string)parameter, out guid);
}
return false;
}
The ultimate goal being that if the parameter is a Guid run this method, otherwise move on, in which case it finds the next one. Is there a better way that does not invlove creating an additional route? Or perhaps a better way all around?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不类似:
非保修伪代码/\
Why not something like:
Non warranty'd psuedo code /\