ASP.NET Web API Controller with attribute routing not working without route name

I use attribute routing , but when I specify an empty attribute Route, I get the following error:

405.0 - method not allowed

However, if I add the route name in the attribute, for example [Route("bar")], everything will work as expected.

Why does one of these action methods work properly while the other gives a 405 error ?

[System.Web.Http.RoutePrefix("foo")]
public partial class MyController : ApiController
{
   [System.Web.Http.HttpPost]
   [System.Web.Http.Route("bar")] // I am able to POST to /foo/bar
   public async Task<MyResponseModel> BarMethod([FromBody]MyArgumentsModel arguments)
   {

   }

   [System.Web.Http.HttpPost]
   [System.Web.Http.Route] // Error when I POST to /foo, "Method Not Allowed"
   public async Task<MyResponseModel> FooMethod([FromBody]MyArgumentsModel arguments)
   {

   }
}

Any ideas on what I might lose?

+4
source share
2 answers

[Route("")], .

, .

: ASP.NET Web API 2

:

[RoutePrefix("foo")]
public partial class MyController : ApiController {
   //eg POST foo/bar
   [HttpPost]
   [Route("bar")]
   public async Task<MyResponseModel> BarMethod([FromBody]MyArgumentsModel arguments) {
      //...
   }

   //eg POST foo    
   [HttpPost]
   [Route("")]
   public async Task<MyResponseModel> FooMethod([FromBody]MyArgumentsModel arguments) {
       //...
   }
}
+2

. , , MapHttpRoute.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(name:"DefaultApi", 
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional } );
    }
}
+1

Source: https://habr.com/ru/post/1655175/


All Articles