【问题标题】:Web API Returning a 405. Shouldn't it be a 404?Web API 返回 405。不应该是 404 吗?
【发布时间】:2015-08-24 06:59:52
【问题描述】:

我有一个支持 GET(按 id)和 POST(带有模型)的 VendorsController。当通过预期路线调用时,它们按预期工作。但是,我注意到如果我在 POST 路由中添加一个 id(即,将“/5”添加到“api/vendors”),我会得到一个 405,带有

响应正文 =

{ "Message": "请求的资源不支持 http 方法 'POST'。" }

这不应该是 404 Not Found 吗? VendorsController 确实支持 POST,但不支持该 URL。

假设 404 是正确的,如何更新我的路线以返回 404 而不是 405?我相信我可以实现自定义 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 });
    }
}

返回 201 的 URL:POST http://localhost/api/vendors

返回 405 的 URL:POST http://localhost/api/vendors/5 带有和不带有请求正文的返回 405。

【问题讨论】:

    标签: rest asp.net-web-api asp.net-web-api2 asp.net-web-api-routing


    【解决方案1】:

    我认为 405 是正确的,因为您有一个可以处理该 URL 的资源 - 您的 GET。

    如果您没有该资源的 GET,那么 404 将是正确的。

    并不是说 VendorController 不支持 POST,而是说您尝试访问的特定资源不支持 POST。

    【讨论】:

      猜你喜欢
      • 2020-11-12
      • 2015-04-26
      • 2014-05-07
      • 1970-01-01
      • 2020-12-16
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多