When methods have the name …Async the exception “System.InvalidOperationException: No route matches the supplied values” occurs

核能气质少年 提交于 2021-02-11 15:40:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!