[英]Want to get 405 (Method Not Allowed) instead of 404
I am trying to get 405 errors when a valid route is supplied but the HTTP method is not found. 当提供有效路由但未找到HTTP方法时,我试图获得405错误。 Currently, the application returns 404s as it requires both the route and method to match on the function (expected behaviour in MVC).
目前,应用程序返回404s,因为它需要路由和方法来匹配函数(MVC中的预期行为)。
[HttpGet("api/action")]
public IActionResult ActionGet()
{
// code
}
[HttpPost("api/action")]
public IActionResult ActionPost()
{
//code
}
In this example, if I do a DELETE
or PUT
request it won't route to either of those functions and just return a 404. 在此示例中,如果我执行
DELETE
或PUT
请求,它将不会路由到这些函数中的任何一个,只返回404。
My current solution is to create a function in every controller which has all the routes hardcoded to catch the request no matter what HTTP method is used. 我目前的解决方案是在每个控制器中创建一个函数,无论使用什么HTTP方法,都有硬编码的所有路由来捕获请求。 This will then just throw a 405 error.
这将导致405错误。
[Route("api/action", Order = 2)]
public IActionResult Handle405()
{
return StatusCode(405);
}
However, I don't really like this way too much as it duplicates the code over several controllers and the hardcoded route list needs to be updated every time a new action is created in the controller. 但是,我不太喜欢这种方式,因为它复制了几个控制器上的代码,并且每次在控制器中创建新操作时都需要更新硬编码路由列表。
Is there a cleaner solution available to handle the routes in the way I want? 是否有更清洁的解决方案可以按照我想要的方式处理路线? Such as using attributes or filters?
比如使用属性还是过滤器?
Since ASP.NET Core 2.2 , the MVC services
support your desired behavior by default. 自ASP.NET Core 2.2起 ,
MVC services
默认支持您所需的行为。 Make sure that the compatibility version of the MVC services is set to Version_2_2
within the ConfigureServices
method. 确保在
ConfigureServices
方法中将MVC服务的兼容版本设置为Version_2_2
。
Startup.cs 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);
}
For demonstration purposes, I have created an API controller similar to yours. 出于演示目的,我创建了一个类似于您的API控制器。
ActionsController.cs 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 Request 获取请求
GET /api/actions/action HTTP/1.1
Host: localhost:44338
200 ActionGet
200 ActionGet
POST Request POST请求
POST /api/actions/action HTTP/1.1
Host: localhost:44338
200 ActionPost
200 ActionPost
PUT Request PUT请求
PUT /api/actions/action HTTP/1.1
Host: localhost:44338
405 Method Not Allowed
405方法不允许
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.