I am trying to get 405 errors when a valid route is supplied but the HTTP method is not found. Currently, the application returns 404s as it requires both the route and method to match on the function (expected behaviour in 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.
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. This will then just throw a 405 error.
[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?