Search code examples
asp.netasp.net-web-apiasp.net-web-api2asp.net-web-api-routing

ASP.NET Web Api 2 - GET with parameters not supported


I want to do a simple REST API for a functionality my webservice will expose.

[RoutePrefix("companies")]
public class CompaniesController : BaseApiController {

    [HttpGet, Route("{companyId:int}")]
    public CustomResponse Get(int companyId) { }

    [HttpPost]
    public CustomResponse Post(CompanySaveViewModel model) { }

    [HttpDelete, Route("{companyId:int}"]
    public CustomResponse Delete(int companyId) { }
}

Ok, this should be working. POST method is working fine. However, when I try to call GET and/or DELETE methods, I got the message below:

I'm trying to call those methods using the given URLs:

http://localhost:11111/api/companies/1 [GET]

http://localhost:11111/api/companies/1 [DELETE]

enter image description here

POST is working fine. When I try to call GET without parameters, it works fine as well. The problem appears when I have any kind of parameter for GET/DELETE methods. What could be the problem here?

Thank you all for the help!


Solution

  • Try adding a route to your POST action:

    [HttpPost, Route("")]
    public CustomResponse Post(CompanySaveViewModel model) { }
    

    This will ensure consistency in your routing definitions: either you use attribute based routing, or you use the global convention based routing (personally I prefer explicit attribute based routing). I would also recommend you to avoid mixing the two types of routes and remove the convention based route from your config:

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

    Also don't forget to enable attribute based routing when bootstrapping:

    config.MapHttpAttributeRoutes();
    

    Here's a nice overview of attribute based routing that I would recommend you going through.