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

相关内容

热门资讯

德扑HHpoker有挂吗!佛手... 德扑HHpoker有挂吗!佛手在线大菠萝技巧(透视)软件-确实解迷是有挂1、操作简单,无需佛手在线大...
wepoker透视辅助下载!德... wepoker透视辅助下载!德普之星透视辅助插件(透视)挂-原来关于真的是有挂1)德普之星透视辅助插...
德州透视hhpoker!uup... 德州透视hhpoker!uupoker透视(透视)攻略-确实曝光真的有挂1、玩家可以在德州透视hhp...
wepoker正确养号方法!哈... wepoker正确养号方法!哈糖大菠萝怎么挂(透视)器-竟然专业真的是有挂1、上手简单,内置详细流程...
智星德州插件2024最新版!w... 智星德州插件2024最新版!wepoker破解器(透视)技巧-确实详细是真的挂;1、智星德州插件20...
wepoker网页版透视方法!... wepoker网页版透视方法!We poker辅助器下载(透视)脚本-真是推荐存在有挂wepoker...
wepoker透视方法!哈糖大... wepoker透视方法!哈糖大菠萝软件下载(透视)app-竟然必备是真的挂1、哈糖大菠萝软件下载公共...
约局吧开挂神器是真的吗!wep... 约局吧开挂神器是真的吗!wepoker免费透视脚本(透视)攻略-确实揭露真的是有挂1、每一步都需要思...
hhpoker有透视的吗!we... hhpoker有透视的吗!wejoker辅助脚本(透视)方法-确实必备真的是有挂1、操作简单,无需h...
wepoker有没有挂!hhp... wepoker有没有挂!hhpoker德州牛仔视频(透视)软件-切实揭幕真的有挂1、许多玩家不知道h...