我正在尝试使用路由在我的 ASP.NET MVC 应用程序中实现本地化。
例如:
www.example.com/Home/Index
- 将显示默认文化的内容。
www.example.com/en/Home/Index
- 将显示英文内容。
www.example.com/ru/Home/Index
- 俄语等等...
因此,我为每个操作创建了本地化属性:
public class LocalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.RouteData.Values["lang"] != null && !String.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString()))
{
var lang = filterContext.RouteData.Values["lang"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
}
else
{
var langHeader = String.Empty;
langHeader = filterContext.HttpContext.Request.UserLanguages[0];
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(langHeader);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
}
base.OnActionExecuting(filterContext);
}
}
我将该属性添加到我的控制器中的每个操作中。
并注册路线:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Localization",
"{lang}/{controller}/{action}/{id}",
new { lang = "en-US", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
导航到www.example.com/About/Contacts
工作正常。但是当我导航到www.example.com/en/About/Contacts
或类似的东西时,我得到404 error
:找不到资源。那么,可能是什么问题?
在此先感谢您的帮助!