为什么 http get 方法在 asp.net web api 中接受 http post 请求?

Rik*_*iki 1 c# asp.net-core asp.net-core-webapi asp.net-core-routing

我有HTTP-GET一个如下所示的方法

[Route("api/[controller]")]
[ApiController]
public class CityController : ControllerBase
{
    public ActionResult Get(int id)
    {
        try
        {
            var city = new { CityName = "Gotham" };
            return Ok(city);
        }
        catch(Exception ex)
        {
            return StatusCode(500);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

对于这两种类型的请求

要求:

GET http://localhost:49915/api/city
POST http://localhost:49915/api/city
Run Code Online (Sandbox Code Playgroud)

回复:

status: 200 OK
-------------------
{
    "cityName": "Gotham"
}
Run Code Online (Sandbox Code Playgroud)

现在我的问题是,

  1. 既然它是 a GET,它应该接受 a 吗POST?
  2. 它不应该返回 405 状态代码吗?为什么不返回?(至少我期待)
  3. 在这种情况下,如果我必须返回405该怎么办?

Nko*_*osi 5

既然它是 GET,它应该接受 POST 吗?

虽然您由于操作名称和基于约定的路由而假设它是 get,但您会误认为控制器已针对属性路由进行了修饰。

[Route("api/[controller]")]
Run Code Online (Sandbox Code Playgroud)

因此,如果匹配,则忽略基于约定的路由。请注意,PUT和DELETE

PUT http://localhost:49915/api/city
DELETE http://localhost:49915/api/city
Run Code Online (Sandbox Code Playgroud)

也应该采取同样的行动。

它不应该返回 405 状态代码吗?为什么不返回?(至少我期待)

由于没有为该操作给出任何指令,因此该操作按照设计与两个调用相匹配。

[Route("api/[controller]")]
[ApiController]
public class CityController : ControllerBase {
    // GET api/city?id=2 //Note id would be optional as a query variable.
    [HttpGet]
    public ActionResult Get(int id) {
        try {
            var city = new { CityName = "Gotham" };
            return Ok(city);
        } catch(Exception ex) {
            return StatusCode(500);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在就位HttpGet,如果

POST http://localhost:49915/api/city
Run Code Online (Sandbox Code Playgroud)

或者执行另一个 HTTP 方法,您将收到 405 错误,因为路径匹配但方法不匹配。

在这种情况下,如果我必须返回405该怎么办?

属性路由到位后,框架将为您完成此操作,因此您无需再做任何事情。

参考ASP.NET Core 中控制器操作的路由

混合路由:属性路由与传统路由

两种路由系统的区别在于URL与路由模板匹配后的处理过程。在传统路由中,匹配的路由值用于从所有传统路由操作的查找表中选择操作和控制器。在属性路由中,每个模板已经与一个操作相关联,不需要进一步查找。