Multiple actions were found that match the request [duplicate]

我的梦境 提交于 2019-12-01 21:07:47

The problem is in the order that the routes are loaded. If they are like this:

// A route that enables RPC requests
routes.MapHttpRoute(
    name: "RpcApi",
    routeTemplate: "rpc/{controller}/{action}",
    defaults: new { action = "Get" }
);

// Default route
routes.MapHttpRoute(
    name: "Default",
    routeTemplate: "{controller}/{id}",
   defaults: new { id =  RouteParameter.Optional }
);

It will work fine. First the request will be mapped against the RPC, then against the controller (thaty may have or not an Id).

We can also create custom action selector for Api Controllers as follows, so that that can freely work with complex types with traditional "GET,POST,PUT,DELETE":

 class ApiActionSelector : IHttpActionSelector
    {
        private readonly IHttpActionSelector defaultSelector;

        public ApiActionSelector(IHttpActionSelector defaultSelector)
        {
            this.defaultSelector = defaultSelector;
        }
        public ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor)
        {
            return defaultSelector.GetActionMapping(controllerDescriptor);
        }
        public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
        {
            // Get HttpMethod from current context
            HttpMethod httpMethod = controllerContext.Request.Method;

            // Set route values for API
            controllerContext.RouteData.Values.Add("action", httpMethod.Method);

            // Invoke Action
            return defaultSelector.SelectAction(controllerContext);
        }
    }

And we can register the same in WebApiConfig as :

 config.Services.Replace(typeof(IHttpActionSelector), new
 ApiActionSelector(config.Services.GetActionSelector()));

May help users who are running this kind of issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!