在 asp.net mvc 4 中,我编写了一个自定义异常处理程序,作为名为 HandleCustomError 的属性。
在这个处理程序中,我应该知道当前请求的是哪个操作,然后我就可以知道该操作的返回类型是什么。我将为“返回类型 view() 和 json”返回不同的数据。
但是,现在我有两个同名的操作,一个用于“Get”,另一个用于“Post”。方法“GetMethod”返回错误:“System.Reflection.AmbigouslyMatchException”
public class HandleCustomError : System.Web.Mvc.HandleErrorAttribute
{
public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
//base.OnException(filterContext);
if (filterContext.ExceptionHandled)
{
return;
}
else
{
//Determine the return type of the action
string actionName = filterContext.RouteData.Values["action"].ToString();
Type controllerType = filterContext.Controller.GetType();
var method = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
var returnType = method.ReturnType;
}
....(Omitted)
最佳答案
我还遇到了这个问题,下面的行给出了 Ambigeous 问题
controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
原因是 Controller 有两个同名的方法,其中一个是
[HTTPGET]
和其他iis
[HTTPPOST]
.
为了获得准确的方法,我使用 GetMethods 和 LINQ。 注意:在 Controller 中,对于 get 方法来说,写入 [HTTPGet]**on 操作不是必需的,即如果未写入 HTTpGet,则默认情况下 .net 会将其视为 **[HttpGet]。但对于后期行动来说,这是强制性的。 将使用此属性来查找正确的方法。
步骤 1. 查找请求类型 2.使用反射查找 Action
- 查找请求类型:
var actionName = filterContext.RouteData.Values["action"].ToString(); Type typeOfRequest = filterContext.HttpContext.Request.RequestType.ToLower() =="get"?typeof(HttpGetAttribute):typeof(HttpPostAttribute);
- 查找方法:
var cntMethods = controllerType.GetMethods() .Where(m => m.Name == actionName && ( ( typeOfRequest == typeof(HttpPostAttribute) && m.CustomAttributes.Where(a => a.AttributeType == typeOfRequest).Count()>0 ) || ( typeOfRequest == typeof(HttpGetAttribute) && m.CustomAttributes.Where(a => a.AttributeType == typeof(HttpPostAttribute)).Count() == 0 ) ) ); MethodInfo actionMethodInfo = actionMethodInfo = cntMethods != null && cntMethods.Count() == 1 ? cntMethods.ElementAt(0):null;
引用:https://techatfingers.wordpress.com/2016/06/14/session-state-on-action/
关于asp.net-mvc-4 - asp.net mvc Type.GetMethod 当两个操作同名,但 get 和 post 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25840422/