创建路由时出错

An error occurred while creating a route

我尝试向我的 .NET Core 项目添加一个区域,但我总是看到错误:

RouteCreationException: An error occurred while creating the route with name '(My Area Name)'

我的密码是:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

        routes.MapRoute(
            name: "custom",
            template: "{area:my area name}/{{controller=AdminHome}/{action=Index}/{id?}");
    });
}

然后在配置服务中添加以下代码:

public void ConfigureServices(IServiceCollection services)
{
    //...

    services.AddRouting(); 

    //...
}

我在控制器中添加了:

[Area("My Area Name")]
public class AdminHomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

错误是:

RouteCreationException: An error occurred while creating the route with name 'custom' and template '{area:area name}/{{controller=Home}/{action=Index}/{id?}'. \r\n Microsoft.AspNetCore.Routing.RouteBase..ctor(string template, string name, IInlineConstraintResolver constraintResolver, RouteValueDictionary defaults, IDictionary constraints, RouteValueDictionary dataTokens) \r\n ArgumentException: There is an incomplete parameter in the route template. Check that each '{' character has a matching '}' character. \r\n Parameter name: routeTemplate

如错误消息中所述,路线模板中存在杂散 {,导致其无效

template: "{area:my area name}/{{controller=AdminHome}/{action=Index}/{id?}");
                               ^
                               |
                             here

您还需要重新排列路由顺序以避免路由冲突。

app.UseMvc(routes => {
    routes.MapRoute(
        name: "custom",
        template: "{area:my area name}/{controller=AdminHome}/{action=Index}/{id?}");

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

引用Areas in ASP.NET Core

routes.MapRoute(
    name: "default",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "Home", action = "Index", id = "id?" } 
);
routes.MapRoute(
    name: "persianredditacp",
    template: "{area}/{controller}/{action}/{id?}"
);  

成功了!

我正在使用 .Net Core 3.1 Web API 项目,问题出在我们在控制器顶部指定路由的控制器中,下面是错误的片段,然后是错误的片段正确:

错误

[Route("api/users/{userId/photos")]

在 userId 后遗漏了结尾的“}”,这导致了这个问题。

正在工作

[Route("api/users/{userId}/photos")]

希望对其他人有帮助:)

很多时候,您对许多文件进行了多次更改,然后在 .net 核心中的 Statup.cs 中进行搜索,结果发现您搞砸了新网站上的一个属性 api像这样的方法

[HttpGet("{id:int")]