WebApi Routing not working for Post

4.5k views Asked by At

My WebApiConfig has following routes

      // Web API routes
        config.MapHttpAttributeRoutes();

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

The Post WebApi method has got following Signatures

    [HttpPost]
    public IHttpActionResult Post(Employee emp)
    {
         .....

    }

When i try to call this method i am getting "Method not allowed"

If i change my Post method to following it starts working

    [Route("api/employee/post")]
    [HttpPost]
    public IHttpActionResult Post(Employee emp)
    {
        ...
    }

I am not getting what's the issue. I want this to work with attributes routing. Can anyone suggest what's the issue here. Does GET and Post routes gets confused ?

1

There are 1 answers

0
Rohit Sonaje On BEST ANSWER

Set your default route like below:

config.MapHttpAttributeRoutes(); //this enables attribute routing

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
); //this route is for conventional routing

now you can call your below API like http://{siteurl}/api/employee/ by conventional routing.

[HttpPost]
public IHttpActionResult Post(Employee emp)
{
   ...
}

now you can call your below API like http://{siteurl}/api/employee/post/ by attribute routing:

[Route("api/employee/post")]
[HttpPost]
public IHttpActionResult Post(Employee emp)
{
   ...
}

Here [Route] parameter adds route, which is called as attribute routing. You can find reference here Routing and Action Selection