简体   繁体   English

Web API 返回 405。不应该是 404 吗?

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

I've got a VendorsController that supports GET (by id) and POST (with a model).我有一个 VendorsController,它支持 GET(通过 id)和 POST(带有模型)。 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但是,我注意到如果我在 POST 路由中添加一个 id(即添加“/5”到“api/vendors”),我会得到一个 405,

Response Body =响应正文 =

{ "Message": "The requested resource does not support http method 'POST'." { "Message": "请求的资源不支持 http 方法 'POST'。" } }

Shouldn't this be a 404 Not Found?这不应该是 404 Not Found 吗? The VendorsController does support POST, but not at that URL. VendorsController 确实支持 POST,但不支持该 URL。

Assuming a 404 is correct, how can I update my routes to return a 404 instead of a 405?假设 404 是正确的,我如何更新我的路由以返回 404 而不是 405? I believe I could implement a custom ActionSelector to do this, but that feels like overkill.我相信我可以实现一个自定义的 ActionSelector 来做到这一点,但这感觉有点矫枉过正。

[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 返回 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. URL 返回 405: POST http://localhost/api/vendors/5返回 405 带有和不带有请求正文。

I think 405 is right because you have a resource that can handle that URL - your GET.我认为 405 是正确的,因为您拥有可以处理该 URL 的资源 - 您的 GET。

If you had no GET for that resource then a 404 would be correct.如果您没有该资源的 GET,那么 404 将是正确的。

It's not saying the VendorController doesn't support POST, rather that the specific resource you are trying to reach doesn't support POST.这并不是说 VendorController 不支持 POST,而是您尝试访问的特定资源不支持 POST。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM