Web API Returning a 405. Shouldn't it be a 404?

936 views Asked by At

I've got a VendorsController that supports GET (by id) and POST (with a model). They are working as expected when called through the intended routes. However, I noticed that if I add an id to the POST route (ie add "/5" to "api/vendors"), I get a 405, with

Response Body =

{ "Message": "The requested resource does not support http method 'POST'." }

Shouldn't this be a 404 Not Found? The VendorsController does support POST, but not at that URL.

Assuming a 404 is correct, how can I update my routes to return a 404 instead of a 405? I believe I could implement a custom ActionSelector to do this, but that feels like overkill.

[RoutePrefix("api/Vendors")]
public class VendorsController : ApiController
{
    [Route("")]
    public IHttpActionResult PostVendor([FromBody]Vendor vendor)
    {
        var uri = Url.Link("GetVendorById", 1);
        return Created(uri, vendor);
    }

    //GET by Id
    [Route("{id:int:min(1)}", Name="GetVendorById")]
    public IHttpActionResult GetVendor(int id)
    {
        return Ok(new Vendor() { Id = id });
    }
}

URL returning a 201: POST http://localhost/api/vendors

URL returning a 405: POST http://localhost/api/vendors/5 Returns a 405 both with and without a request body.

1

There are 1 answers

0
iandayman On BEST ANSWER

I think 405 is right because you have a resource that can handle that URL - your GET.

If you had no GET for that resource then a 404 would be correct.

It's not saying the VendorController doesn't support POST, rather that the specific resource you are trying to reach doesn't support POST.