我按照这篇关于ASP.NET MVC 5国际化的文章(由asp.net网站提到): http://afana.me/post/aspnet-mvc-internationalization.aspx
实施后,我只有一个问题无法解决。 在MVC5中,使用网址中的文化(不使用cookie),文化总是默认的,永远不会让用户首选浏览器发送的语言。
更详细: 问题是MapRoute中的文化违约,从网站的默认硬编码文化开始。然后在BeginExecuteCore中,RouteData.Values [" culture"]总是充满默认文化,永远不会从Request.UserLanguages获取文化。 RouteData.Values [" culture"]即使文化不存在于网址中,也会填充,例如,首先访问网站根目录。
如何正确更改此行为?
也许创造2条路线,一条没有文化?
相关代码:
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new {culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "Index", id = UrlParameter.Optional }
);
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string cultureName = RouteData.Values["culture"] as string;
// Attempt to read the culture cookie from Request
if (cultureName == null)
cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ? Request.UserLanguages[0] : null; // obtain it from HTTP header AcceptLanguages
//...
}
答案 0 :(得分:0)
我发现了解决方案,需要添加另一个mapRoute(mvc默认为站点root访问权限),并为文化路由注入默认值,路由顺序很重要,现在一切正常:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Route order is important! First need to put culture route.
//support for diferent languages/cultures
routes.MapRoute(
name: "CultureEnabled",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { /*culture = CultureHelper.GetDefaultCulture(),*/ controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}