创建路由时出错

A.J*_*A.J 8 c# asp.net-mvc-routing asp.net-mvc-areas asp.net-core

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

RouteCreationException:创建名称为“(我的区域名称)”的路线时出错

我的代码是:

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?}");
    });
}
Run Code Online (Sandbox Code Playgroud)

在配置服务中,我添加了以下代码:

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

    services.AddRouting(); 

    //...
}
Run Code Online (Sandbox Code Playgroud)

在控制器中我添加了:

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

错误是:

RouteCreationException:创建名称为“custom”且模板为“{area:area name}/{{controller=Home}/{action=Index}/{id?}”的路由时出错。\r\n Microsoft.AspNetCore.Routing.RouteBase..ctor(string template, string name, IInlineConstraintResolver constraintResolver, RouteValueDictionary defaults, IDictionary constraint, RouteValueDictionary dataTokens) \r\n ArgumentException: 路由模板中有一个不完整的参数。检查每个 '{' 字符是否有一个匹配的 '}' 字符。\r\n 参数名称:routeTemplate

Nko*_*osi 12

如错误消息中所述,您{在路由模板中有一个使其无效的流浪

template: "{area:my area name}/{{controller=AdminHome}/{action=Index}/{id?}");
                               ^
                               |
                             here
Run Code Online (Sandbox Code Playgroud)

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

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?}");
});
Run Code Online (Sandbox Code Playgroud)

ASP.NET Core 中的参考区域


小智 5

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

错误

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

在 userId 之后错过了关闭的“}”,这导致了这个问题。

在职的

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

希望它可以帮助其他人:)


Tom*_*kel 5

很多时候,您对许多文件进行了多次更改,然后在 .net core 中的 Statup.cs 中进行搜索,最终却发现您弄乱了新的 Web api 方法上的属性,如下所示

[HttpGet("{id:int")]  
Run Code Online (Sandbox Code Playgroud)