【问题标题】:System.InvalidOperationException: No route matches the supplied valuesSystem.InvalidOperationException:没有路由与提供的值匹配
【发布时间】:2021-05-24 11:45:30
【问题描述】:

我正在尝试通过 post 方法在 .NET 5.0 中调用 API,但得到 System.InvalidOperationException: No route 与提供的值匹配。你能帮我做同样的事情吗?

我的代码

[Route("api/[controller]")]
[ApiController]
public class CommonController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly ILanguages _Languages;
    public CommonController(ILanguages Languages, IConfiguration configuration)
    {
        _Languages = Languages;
        _configuration = configuration;
    }


    [HttpGet, Route("GetLanguages")]
    public Languages GetLanguages()
    {
        try
        {
            return _Languages.GetLanguages();

        }
        catch (Exception)
        {

            throw;
        }

    }
}

【问题讨论】:

  • 请显示您的请求链接和您的 webAPI 路由配置(如果有一些特定的)
  • app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
  • 你是在做 GET 还是 POST 请求?因为您的GetLanguages 操作被标记为POST
  • @demo 其实我想要 GET 但都尝试了但同样的问题

标签: c# api .net-core .net-5


【解决方案1】:

您是否尝试过在控制器级别使用 RoutePrefix 属性? Controller 级别的 Route 属性用作控制器内没有设置 Route 属性的那些操作的后备路由。在您的情况下,您似乎想要实际使用“api/[controller]”作为在操作级别定义的后一个路由的前缀。

在此链接中查看有关 RoutePrefix 和 Route 属性的更多信息:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

【讨论】:

    【解决方案2】:

    将方法转换为异步时出现此错误。 更新 Startup.cs 中的 AddControllers 函数对我有用。

    这里的解决方案:ASP.NET CORE, Web API: No route matches the supplied values

    问题原因:在运行时,异步后缀被删除。

    services.AddControllers(
        options => {
            options.SuppressAsyncSuffixInActionNames = false;
        }
    );
    

    【讨论】:

      猜你喜欢
      • 2019-02-03
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多