c# - 带有文化 url 的 ASP.Net MVC 5 路由

标签 c# asp.net asp.net-mvc asp.net-mvc-routing asp.net-mvc-5

我关注了this指南,它与我的语言支持配合得很好。网址如 http://domain.com:33982/en-us/Test效果很好。

但是我的问题是我希望它能够与 http://domain.com:33982/Test以及。如果没有链接中的文化,我无法弄清楚如何路由它...... 我在 RouteConfig.cs 中的路线

            routes.MapRoute(
            name: "Default",
            url: "{culture}/{controller}/{action}/{id}",
            defaults: new { culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        routes.MapRoute(
name: "MissingCulture",
url: "{controller}/{action}/{id}",
defaults: new { culture = CultureHelper.GetDefaultCulture(), controller = "Test", action = "PageMissing", id = UrlParameter.Optional }
);

我真的不明白为什么它不起作用。当我转到/Test 时,只是将我重定向到默认的主页/索引。

有什么建议吗?谢谢

最佳答案

这是因为第一条和第二条路线都匹配。可选参数会导致应用程序选择第一个匹配的参数:因此始终会选择第一个参数。

试试这个:

        routes.MapRoute( name: "DefaultWithCulture"
                       , url: "{culture}/{controller}/{action}/{id}"
                       , defaults: new { culture = "en-us", controller = "Home", action = "Index", id = UrlParameter.Optional }
                       , constraints: new { culture = "[a-z]{2}-[a-z]{2}" }
        );

        routes.MapRoute( name: "Default"
                       , url: "{controller}/{action}/{id}"
                       , defaults: new { culture = "xx-xx", controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

它在这里起作用(返回它们背后的文化):

http://host/ (en-us)
http://host/Home/Index (xx-xx)
http://host/zh-cn/Home/Index (zh-cn)

关于c# - 带有文化 url 的 ASP.Net MVC 5 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21235226/

相关文章:

c# - OpenID 提供商作为身份验证代理

asp.net - 如何在 PreRender 上修改 ASP.NET 页面的原始 HTML?

asp.net - 在自主机模式下获取当前的 owin 上下文

asp.net-mvc - 为什么 WebSecurity.Logout *立即*将 IPrincipal.User 更新为空用户

asp.net-mvc - 我如何使用 ModelBinder 来更正用户可以看到的值?

c# - 异步 TPL 死锁与第三方 lib aka wild goose chase

c# - 更新文件更改的数据?

asp.net - 如何分析 ASP.NET/IIS 管道

c# - Razor HTML Helpers 在 Nop Commerce 插件中给出智能感知错误

C#解析json中的数组