步骤1:打开VS2015新建测试项目。
步骤2:创建资源文件 App_GlobalResources下。
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;
}
}
}
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