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

相关内容

热门资讯

经调查!如何下载wepoker... 经调查!如何下载wepoker安装包(透视)一贯确实有挂(有挂透视开挂辅助下载)-哔哩哔哩暗藏猫腻,...
截至目前!wepoker底牌透... 截至目前!wepoker底牌透视脚本,红龙poker辅助,操作教程(存在有挂)-哔哩哔哩1、不需要A...
据通报!wepoker黑侠辅助... 据通报!wepoker黑侠辅助器正版下载(透视)一直是有挂的(今日头条开挂辅助插件)-哔哩哔哩wep...
这一现象值得深思!wepoke... 这一现象值得深思!wepoker私人定制透视(透视)一贯确实有挂(有挂详细开挂辅助下载)-哔哩哔哩1...
据玩家消息!pokemmo脚本... 据玩家消息!pokemmo脚本辅助,hhpoker真的假的,步骤教程(有挂分析)-哔哩哔哩1、pok...
围绕透视问题!wepoker怎... 围绕透视问题!wepoker怎么设置房间,wepoker安装教程,要领教程(有挂技术)-哔哩哔哩1)...
有玩家发现!wepoker私人... 有玩家发现!wepoker私人局辅助器怎么用(透视)果然真的是有挂(真是有挂开挂辅助下载)-哔哩哔哩...
经核实!hhpoker有透视功... 经核实!hhpoker有透视功能吗(透视)其实真的有挂(有挂秘诀开挂辅助软件)-哔哩哔哩1、完成hh...
长期以来!poker红龙辅助,... 长期以来!poker红龙辅助,pokemmo脚本辅助,烘培教程(有挂方略)-哔哩哔哩1、上手简单,内...
近日!pokemmo辅助器手机... 近日!pokemmo辅助器手机版下载(透视)其实是有挂的(的确有挂开挂辅助软件)-哔哩哔哩1、pok...