When I run my api, and my ErrorController will ignore and does not work. here is my program.cs class
app.UseExceptionHandler("/error");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
my authController:
[ApiController]
[AllowAnonymous]
public class AuthController:ControllerBase
{
...
...
[HttpPost]
[Route("AccessToken")]
public async Task<IActionResult> AccessToken([FromBody] LoginCredential? credential)
{
var user = await
_userRepository.FindUserByEmail(credential.Email,credential.Password);
if (user is null)
{
return new BadRequestObjectResult(new { Message = "Login Failed" });
}
var accessToken = GenerateToken(user);
return Ok(new { AccessToken = accessToken });
}
and finally ErrorsController class:
public class ErrorsController:ControllerBase
{
[Route("/Error")]
[HttpGet]
public IActionResult Error()
{
return Problem();
}
}
however when I delete [Httpget] in ErrorsController I get "Ambiguous HTTP method for action" error.
CodePudding user response:
As it has been explained in this document:
Don't mark the error handler action method with HTTP method attributes, such as HttpGet. Explicit verbs prevent some requests from reaching the action method. For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its IgnoreApi property to true.
If you add [HttpGet] Attribute on your Error method, when you get error in a post method,It won't get into the method and throw 405 Error,and if you delete the [HttpGet] Attribute without adding [ApiExplorerSettings] ,swagger would throw Ambiguous HTTP method for action
I tried as below in my case:
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{ app.UseSwagger(); app.UseSwaggerUI();
}
app.UseExceptionHandler("/Error");
//make sure there're on other error handle middlewares behind it
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
The controller:
[ApiController]
public class ErrorController : ControllerBase
{
[Route("/error")]
[ApiExplorerSettings(IgnoreApi = true)]
public IActionResult HandleError()
{
return Problem();
}
}
Result:
When it comes to handling validation failure error response,you could check this document for more details