C# 所有操作(而不仅仅是根操作)的URL段的默认值?
我正在用多种语言本地化我的静态网站。我已经添加了两个资源(.resx)文件,C# 所有操作(而不仅仅是根操作)的URL段的默认值?,c#,asp.net,asp.net-mvc,localization,C#,Asp.net,Asp.net Mvc,Localization,我正在用多种语言本地化我的静态网站。我已经添加了两个资源(.resx)文件,Strings.resx和Strings.es.resx 我有一个RouteConfig,像这样: var language = System.Threading.Thread.CurrentThread.CurrentUICulture.Name; routes.MapRoute( name: "Default", url: "{lang}/{controller}/{action}/{id}",
Strings.resx
和Strings.es.resx
我有一个RouteConfig,像这样:
var language = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
routes.MapRoute(
name: "Default",
url: "{lang}/{controller}/{action}/{id}",
constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" },
defaults: new { lang = language, controller = "app", action = "index", id = UrlParameter.Optional }
);
我还有以下过滤器设置:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new LocalizationAttribute("en"), 0);
}
}
使用此属性的:
public class LocalizationAttribute : ActionFilterAttribute
{
private string mDefaultLanguage = "en";
public LocalizationAttribute(string defaultLanguage)
{
mDefaultLanguage = defaultLanguage;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string lang = (string)filterContext.RouteData.Values["lang"] ?? mDefaultLanguage;
if (lang != mDefaultLanguage)
{
try
{
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
}
catch (Exception)
{
throw new NotSupportedException(string.Format("ERROR: Invalid language code '{0}'.", lang));
}
}
}
}
当我用这个导航到我的主页时,它默认为英语,URL看起来像http://example.com/
当我导航到任何其他操作时,它会将URL更改为:http://example.com/en-us/register
,例如。如果我从URL中删除en-us
,并将其设置为http://example.com/register
,我得到了一个404
注意,如果我将URL更改为
http://example.com/es/
和http://example.com/es/register
,它按预期工作。我只希望默认为英语,即使没有提供en
或en-us
。您可以添加多个路由映射,因为您的默认设置为en
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {controller = "Home or app", action = "index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{lang}/{controller}/{action}/{id}",
constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" },
defaults: new { lang = language, controller = "app", action = "index", id = UrlParameter.Optional }
);
您是否尝试过在url中添加没有语言的其他路由,然后在默认值中指定语言?将需要在第一条路线后放入,以防止其与所有内容匹配
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { lang = "en", controller = "app", action = "index", id = UrlParameter.Optional }
);
有两件事可以让这成为答案。第一:将其中一条路由重命名为非
默认值
,因为两条路由不能具有相同的名称。第二,将catch allDefault
路由移动到本地化路由下方,以便首先尝试使用本地化路由。可能重复的