MyModule類的具體實現:web
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Web; using System.Web.Routing; namespace MVC4多語言IHttpModule實現.Lang { public class MyModule: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; } } }
而後添加路由 規則:mvc
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MVC4多語言IHttpModule實現 { // 注意: 如需啟用 IIS6 或 IIS7 傳統模式的說明, // 請造訪 http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);//在此方法中添加路由規則
BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterAuth(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace MVC4多語言IHttpModule實現 { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 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})?$" } //參數約束
); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }