asp.net mvc Type.GetMethod当两个动作同名时,但获取和发布

Gua*_*Wan 7 post get asp.net-mvc-4

在asp.net mvc 4中,我编写了一个自定义的异常处理程序,作为名为HandleCustomError的属性.

在这个处理程序中,我应该知道当前请求的动作,然后我就可以知道这个动作的返回类型是什么.我将返回"return type view()和json"的不同数据.

但是,现在我有两个同名的动作,但一个是"Get",另一个是"Post".方法"GetMethod"返回错误:"System.Reflection.AmbiguousMatchException"

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)
Run Code Online (Sandbox Code Playgroud)

Jok*_*ker 0

正如您所提到的,您有两个同名的操作,但一个用于“Get”,另一个用于“Post”,您可以尝试第一个操作的[HttpGet]和第一个操作的[HttpPost]或如果您的操作满足来自多个动词的请求,您可以尝试类似的操作

[HttpGet, HttpPost] or [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
Run Code Online (Sandbox Code Playgroud)

例如,如果您的函数名称是 GetMethod 那么请尝试这样

[HttpGet]
Public ActionResult GetMethod()
{
   //do something ...
}

[HttpPost]
Public ActionResult GetMethod()
{
   //do something ...
}
Run Code Online (Sandbox Code Playgroud)