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

Attribute Routing in Web API with RoutePrefix - Strange error


    [RoutePrefix("ServiceRequest")]
    public class ServiceRequestController : ApiController
    {
        [HttpPost]
        [Route("")]
        public IHttpActionResult Post([FromBody]ServiceRequest.Models.ServiceRequest serviceRequest)
        {
            return Ok();
        }
    }

I use an empty Route() for a POST in WebAPI and invoke

`http://localhost.com:59985/ServiceRequest/

This throws an error stating HTTP Error 405.0 - Method Not Allowed and most likely causes given were

  • The request sent to the Web server used an HTTP verb that is not allowed by the module configured to handle the request

    (or)

    A request was sent to the server that contained an invalid HTTP verb

    (or)

    The request is for static content and contains an HTTP verb other than GET or HEAD

    (or)

    A request was sent to a virtual directory using the HTTP verb POST and the default document is a static file that does not support HTTP verbs other than GET or HEAD.

However if use Route("Test"), the method just works fine as like below:

[POST] to http://localhost.com:59985/ServiceRequest/Test -- works fine. (Route is [Route("Test")])

[POST] to http://localhost.com:59985/ServiceRequest ------- does not work (Route is [Route("")]

Is empty Route not allowed for POST ? Any ideas what is wrong here ?


Solution

  • Turns out to be some issue because the [RoutePrefix("ServiceRequest")] had the same name as the controller name.

    When I changed the [RoutePrefix()] everything worked fine as before.