想要得到 405 (Method Not Allowed) 而不是 404

Want to get 405 (Method Not Allowed) instead of 404

我试图在提供有效路由但未找到 HTTP 方法时收到 405 错误。目前,应用程序 returns 404s 因为它需要路由和方法来匹配函数(MVC 中的预期行为)。

[HttpGet("api/action")]
public IActionResult ActionGet()
{
    // code
}

[HttpPost("api/action")]
public IActionResult ActionPost()
{
    //code
}

在这个例子中,如果我执行 DELETEPUT 请求,它不会路由到这两个函数中的任何一个,而只是 return 一个 404。

我目前的解决方案是在每个控制器中创建一个函数,无论使用何种 HTTP 方法,该函数都对所有路由进行硬编码以捕获请求。然后这将引发 405 错误。

[Route("api/action", Order = 2)]
public IActionResult Handle405()
{
    return StatusCode(405);
}

但是,我不太喜欢这种方式,因为它会在多个控制器上重复代码,并且每次在控制器中创建新操作时都需要更新硬编码路由列表。

是否有更简洁的解决方案可以按照我想要的方式处理路由?比如使用属性或者过滤器?

由于 ASP.NET Core 2.2MVC services 默认支持您想要的行为。确保在 ConfigureServices 方法中将 MVC 服务的兼容版本设置为 Version_2_2

Startup.cs

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

例子

出于演示目的,我创建了一个类似于您的 API 控制器。

ActionsController.cs

[Route("api/[controller]")]
[ApiController]
public class ActionsController : ControllerBase
{
    [HttpGet("action")]
    public IActionResult ActionGet()
    {
        return Ok("ActionGet");
    }

    [HttpPost("action")]
    public IActionResult ActionPost()
    {
        return Ok("ActionPost");
    }
}

GET 请求

GET /api/actions/action HTTP/1.1
Host: localhost:44338

200 ActionGet

POST请求

POST /api/actions/action HTTP/1.1
Host: localhost:44338

200 ActionPost

PUT 请求

PUT /api/actions/action HTTP/1.1
Host: localhost:44338

405 Method Not Allowed