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”动作方法,添加中文版本和英

相关内容

热门资讯

透视ai代打!wpk辅助软件多... 《透视ai代打!wpk辅助软件多少钱一个,hhpoker德州有挂吗,专业教程(最初是真的有挂)》 w...
透视模拟器!aapoker辅助... WePoker透视辅助版本稳定性对比与推荐‌:透视模拟器!aapoker辅助插件工具下载,wepok...
透视真的!wpk透视脚本下载,... 透视真的!wpk透视脚本下载,hhpoker外挂靠谱吗,德州教程(切实真的是有挂);支持2-10人实...
透视插件!wepoker辅助器... 透视插件!wepoker辅助器是真的的吗,wepokerplus开挂,新2025教程(最初真的有挂)...
透视有挂!红龙poker透视,... 透视有挂!红龙poker透视,hhpoker真的有透视吗,软件教程(起初是有挂);大神普及一款德州a...
透视ai代打!德普之星app安... 透视ai代打!德普之星app安卓版破解版,德普之星有辅助软件吗,普及教程(固有有挂);德普之星app...
辅助透视!wpk脚本辅助器,w... 辅助透视!wpk脚本辅助器,wepoker软件靠谱么,爆料教程(起初有挂)关于wpk脚本辅助器的基本...
透视新版!aapoker辅助插... 透视新版!aapoker辅助插件工具,来玩app破解版,曝光教程(本然是有挂);aapoker辅助插...
透视最新!aapoker辅助挂... 透视最新!aapoker辅助挂,hhpoker辅助挂下载,我来教教你(固有有挂)1、许多玩家不知道a...
透视透视!智星菠萝辅助器,we... 透视透视!智星菠萝辅助器,wepoker游戏下载,插件教程(其实是真的有挂);超受欢迎的智星菠萝辅助...