Adding an explicit action route to ASP.NET Web API Controller

后端 未结 2 952
情深已故
情深已故 2021-02-19 00:14

I have an ASP.NET Web API project with an ApiController that provides a User endpoint with the following actions:

GET /api/User
POST /a         


        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 01:06

    The default route does not include the action.

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

    It selects actions based on the controller, HTTP verb and the parameter, or lack of parameter, in the route. So, it is finding the correct controller and looking for a GET action with no parameter. It finds two.

    You should add an additional route that includes the action. This is either done with attribute based routing as Kiran mentioned or by convention based routing. For convention based routing, the route is typically placed in the Application_start() method of WebApiConfig.cs. More specific routes go before general routes, so your routes would look something like this:

    config.Routes.MapHttpRoute(
                    name: "ApiWithAction",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
     config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    

提交回复
热议问题