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

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 ?

Upvotes: 1

Views: 1483

Answers (2)

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.

Upvotes: 1

djikay
djikay

Reputation: 10628

[RoutePrefix] adds a prefix to your routes. So, in your example, if you don't specify the [RoutePrefix] attribute, then by convention your route would be:

.../api/ServiceRequest

By adding the [RoutePrefix] attribute you are saying that the routes in this controller will be prefixed by the specified route, i.e. you are effectively changing your route to:

.../api/ServiceRequest/ServiceRequest

Could this be the reason for your issue? I'm not sure having a RoutePrefix with the same name as the controller was necessarily the problem, but I could be wrong -- I'm still pretty new at this stuff.

Upvotes: 1

Related Questions