ASP.Net MVC 6 路由错误

ASP.Net MVC 6 route error

我有 ASP.Net MVC 6 应用程序

我添加了如下路线:

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

});

但我收到如下错误:

System.InvalidOperationException: The route parameter 'controller' has both an inline default value and an explicit default value specified. A route parameter cannot contain an inline default value when a default value is specified explicitly, consider removing one of them.

有什么建议吗?

错误消息告诉您需要做什么

您可以删除内联默认值

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

});

或删除显式默认值模板:

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

经过搜索和测试,我找到了一个不错的 post: http://stephenwalther.com/archive/2015/02/07/asp-net-5-deep-dive-routing

并且我像下面这样更新了我的路线,它完美无缺

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

            routes.MapRoute(
              name: "route2",
              template: "statics",
              defaults: new { controller = "Departments", action = "Index" }

             );

            routes.MapRoute(
               name: "route3",
               template: "statics/SYears",
               defaults: new { controller = "SYears", action = "Index" }
            );
            /*
              routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}",
                defaults: new {controller="Statics", action="Index"}
                );

            */
        });

问题是您试图同时定义内联默认值和显式默认值。在定义 template 参数时,= 运算符将分配 defaults,但您随后试图在下一行明确定义默认值。考虑以下因素:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        // Notice the removal of the defaults from the template?
        template: "{controller}/{action}/{id?}",
        defaults: new {Controllers="Statics", action="Index"}
        );

});

另一种方法是使用内联 defaults 定义 template,然后完全省略 defaults 行,如下所示:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        // Notice how we assign the defaults inline, and omit the defaults line?
        template: "{controller=Statics}/{action=Index}/{id?}"
        );    
});