转: ASP.NET MVC 多语言配置

步骤1:打开VS2015新建测试项目。

步骤2:创建资源文件 App_GlobalResources下。

   Resource1.resx
   Resource1.zh-cn.resx
 
步骤3:在WebApplication11.App_Code文件夹下新建类CultureModule

namespace WebApplication11.App_Code

{

public class CultureModule : IHttpModule

{

private CultureInfo currentCulture;

private CultureInfo currentUICulture;

public void Dispose() { }

public void Init(HttpApplication context)

{

context.BeginRequest += SetCurrentCulture;

context.EndRequest += RecoverCulture;

}

private void SetCurrentCulture(object sender, EventArgs args)

{

currentCulture = Thread.CurrentThread.CurrentCulture;

currentUICulture = Thread.CurrentThread.CurrentUICulture;

HttpContextBase contextWrapper = new HttpContextWrapper(HttpContext.Current);

RouteData routeData = RouteTable.Routes.GetRouteData(contextWrapper);

if (routeData == null)

{

return;

}

object culture;

if (routeData.Values.TryGetValue("lang", out culture))

{

try

{

Thread.CurrentThread.CurrentCulture = new CultureInfo(culture.ToString());

Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture.ToString());

}

catch

{ }

}

}

private void RecoverCulture(object sender, EventArgs args)

{

Thread.CurrentThread.CurrentCulture = currentCulture;

Thread.CurrentThread.CurrentUICulture = currentUICulture;

}

}

}

 
步骤4:配置路由

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

 

//以下是新加的路由配置,Begin-----------------------------------------------------------------

routes.MapRoute(

"Globalization", // 路由名称

"{lang}/{controller}/{action}/{id}", // 带有参数的 URL

new { lang = "zh", controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值

new { lang = "^[a-zA-Z]{2}(-[a-zA-Z]{2})?$" } //参数约束

);

//-------------------End------------------------------------------------

 

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

}

步骤5:配置webconfig

 

<system.webServer>

<modules>

<addname="CultureModule"type="WebApplication11.App_Code.CultureModule"/>

<removename="FormsAuthentication" />

</modules>

</system.webServer>

 

步骤6:View里面直接调用

@Resources.Resource1.String1

步骤7:直接运行,搞定!

 

原文地址:http://blog.csdn.net/sky_666/article/details/55667051

转载于:https://www.cnblogs.com/jearay/p/7656352.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值