问题
Steps to reproduce:
- Create a new Web API project
- Create a UsersController with the following code
.
[ApiController]
[Route("[controller]")]
public class UsersController : ControllerBase
{
[HttpGet("{id:int}", Name = nameof(GetUserByIdAsync))]
public async Task<ActionResult<object>> GetUserByIdAsync([FromRoute] int id)
{
object user = null;
return Ok(user);
}
[HttpPost]
public async Task<ActionResult<object>> CreateUserAsync()
{
object user = null;
return CreatedAtAction(nameof(GetUserByIdAsync), new { id = 1 }, user);
}
}
- Call the url POST https://localhost:5001/users
- You will get the exception
System.InvalidOperationException: No route matches the supplied values.
Rename both methods by removing the
Async
from the method names, the methods should look like[HttpGet("{id:int}", Name = nameof(GetUserById))] public async Task<ActionResult<object>> GetUserById([FromRoute] int id) { // ... } [HttpPost] public async Task<ActionResult<object>> CreateUser() { // ... }
Call the url POST https://localhost:5001/users again
- You will receive an empty 201 response
So I'm assuming the error occurs with the method names, any ideas?
回答1:
System.InvalidOperationException: No route matches the supplied values.
To fix above error, you can try to set SuppressAsyncSuffixInActionNames
option to false
, like below.
services.AddControllers(opt => {
opt.SuppressAsyncSuffixInActionNames = false;
});
Or apply the [ActionName]
attribute to preserve the original name.
[HttpGet("{id:int}", Name = nameof(GetUserByIdAsync))]
[ActionName("GetUserByIdAsync")]
public async Task<ActionResult<object>> GetUserByIdAsync([FromRoute] int id)
{
来源:https://stackoverflow.com/questions/62202488/when-methods-have-the-name-async-the-exception-system-invalidoperationexcept