【问题标题】:ASP.Net Core 3.0 app startup exception 'There is an incomplete parameter in the route template'ASP.Net Core 3.0 应用程序启动异常'路由模板中的参数不完整'
【发布时间】:2021-09-01 13:53:55
【问题描述】:

我有一个非常令人困惑的问题,主要是因为我得到的异常非常无用且没有描述性。

我有一个基于 ASP.Net Core 的 API,并且刚刚添加了一个新控制器。我正在使用 ASP.Net Core 3.0,并使用以下方法在 Startup.Configure 中映射我的控制器:

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

但是,在调试中运行 API 时,我在启动时遇到以下异常:

RoutePatternException:路由模板中的参数不完整。检查每个“{”字符是否有匹配的“}”字符。

我删除了控制器并且问题消失了,所以我认为控制器有问题导致端点映射抛出此异常但我看不到它是什么?

【问题讨论】:

    标签: asp.net asp.net-core asp.net-core-3.0


    【解决方案1】:

    只有当我重新配置端点的路由方式时,我才找到了问题的答案。我已经写了这个,以防其他人从 ASP.Net Core 获得任何非描述性异常。在 Startup.Configure 中,我替换了:

    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });

    与:

    app.UseMvc(routes =>
    {
        routes.MapRoute("repo1", "{controller=Repo1Controller}");
        routes.MapRoute("repo2", "{controller=Repo2Controller}");
    }
    

    然后在 Startup.ConfigureServices 中,我添加了:

    services.AddMvc(option => option.EnableEndpointRouting = false);

    下次启动时会出现以下异常:

    RouteCreationException:属性路由信息出现以下错误:对于操作:'MyAPI.Controllers.Repo2Controller.UpdateEntityProperty (MyAPI)'

    错误:路由模板中的参数不完整。检查每个 '{' 字符是否有匹配的 '}' 字符。 (参数'routeTemplate')

    Repo2Controller 我有以下内容:

    [HttpPut("{entityId}/Properties/{propertyId")]
    public IActionResult UpdateEntityProperty(string entityId, string propertyId)
    {
        // Do some stuff
    }
    

    这突出了我在HttpPut 属性中缺少结束} 的事实。一旦我替换了它并返回到原来的端点路由方法,一切正常。

    【讨论】:

      【解决方案2】:

      使用 try catch 包装 Configure() 方法代码,如下所示。

          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
          {
              try
              {
                  ...
      
                  app.UseEndpoints(endpoints =>
                  {
                      endpoints.MapControllers();
                  });
      
                  ...
      
              }
              catch (System.Exception exp)
              {
      
                  throw;
              }
          }
      

      然后调查抛出的异常。在 InnerException->Pattern 下你会发现具体的问题。示例:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 2019-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多