繁体   English   中英

创建路由时出错

[英]An error occurred while creating a route

我尝试向我的 .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?}");
    });
}

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

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

    services.AddRouting(); 

    //...
}

在控制器中我添加了:

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

错误是:

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

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

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?}");
});

ASP.NET Core 中的参考区域

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

错误

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

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

工作

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

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

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 核心中的 Statup.cs 中进行搜索,结果却发现您弄乱了像这样的新 Web api 方法上的属性

[HttpGet("{id:int")]  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM