ASP.NETMVC中多语言区域的路由怎样设置?
创始人
2024-09-19 09:01:12
0
  1. 首先,在 Global.asax.cs 文件中添加以下代码,以设置支持多语言的 Culture 和 UICulture:

protected void Application_BeginRequest() { var lang = ""; var userLanguages = Request.UserLanguages;

if (userLanguages != null && userLanguages.Length > 0)
{
    lang = userLanguages[0].ToLowerInvariant();
}

switch (lang)
{
    case "zh-cn":
        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("zh-CN");
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("zh-CN");
        break;
    case "zh-tw":
        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("zh-TW");
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("zh-TW");
        break;
    default:
        Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
        Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
        break;
}

}

  1. 接下来,在 RouteConfig.cs 文件中,使用属性路由和正则表达式为每个区域配置路由,以及为每个语言设置区域值。例如,为英语和中文配置首页路由,代码如下:

public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapMvcAttributeRoutes();

routes.MapRoute(
    name: "Default",
    url: "{language}/{controller}/{action}/{id}",
    defaults: new { language = "zh-cn", controller = "Home", action = "Index", id = UrlParameter.Optional },
    constraints: new { language = "(en|zh-cn|zh-tw)" }
);

routes.MapRoute(
    name: "Default_en",
    url: "en/{controller}/{action}/{id}",
    defaults: new { language = "en", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default_cn",
    url: "zh-cn/{controller}/{action}/{id}",
    defaults: new { language = "zh-cn", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default_tw",
    url: "zh-tw/{controller}/{action}/{id}",
    defaults: new { language = "zh-tw", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

}

  1. 最后,定义控制器动作方法以响应每条路由。例如,为“Home”控制器中的“Index”动作方法,添加中文版本和英

相关内容

热门资讯

透视免费!pokeplus脚本... 透视免费!pokeplus脚本,wpk俱乐部辅助器,课程教程(有挂实锤)-哔哩哔哩1、透视免费!po...
透视科技!hhpoker俱乐部... 透视科技!hhpoker俱乐部是干嘛的,hhpoker软件可以玩吗,教程书教程(有挂讲解)-哔哩哔哩...
透视讲解!aapoker公共底... 透视讲解!aapoker公共底牌,wepoker底牌透视,模板教程(有挂教学)-哔哩哔哩1、进入到a...
透视软件!德州局脚本,拱趴大菠... 透视软件!德州局脚本,拱趴大菠萝挂哪里,资料教程(有挂总结)-哔哩哔哩1、玩家可以在拱趴大菠萝挂哪里...
透视辅助!约局吧是否有挂,we... 透视辅助!约局吧是否有挂,wepoker分析,机巧教程(有挂教学)-哔哩哔哩小薇(透视辅助)致您一封...
透视线上!大菠萝手游辅助,hh... 透视线上!大菠萝手游辅助,hhpoker是真的还是假的,攻略教程(有挂教学)-哔哩哔哩1、hhpok...
透视肯定!pokemmo脚本,... 透视肯定!pokemmo脚本,wepoker有辅助吗,资料教程(有挂教学)-哔哩哔哩1、wepoke...
透视模拟器!大菠萝免费辅助,w... 透视模拟器!大菠萝免费辅助,wepoker破解工具,法门教程(有挂头条)-哔哩哔哩1、大菠萝免费辅助...
透视安卓版!wepoker有没... 透视安卓版!wepoker有没有机器人,hhpoker脚本下载,课程教程(有挂技巧)-哔哩哔哩wep...
透视安装!wepoker公共底... 透视安装!wepoker公共底牌,pokermaster破解版,模块教程(讲解有挂)-哔哩哔哩1、完...