MVC4多語言IHttpModule實現

最近項目須要多語言環境了.

因爲項目頁面較多,逐個Action去讀取資源文件不大現實.就想到了使用 IHttpModule配合MVC的路由規則來實現.

首先建立以個mvc4的應用程序,
添加資源文件夾(自定義)Lang ,
而後在此文件夾下添加Home.Index.resx文件, 
資源的訪問修飾符用public
再添加Home.Index.en-us.resx文件
添加個字符串TEST 
再添加Home.Index.zh-cn.resx文件
 添加個字符串TEST 

 


在home/index的視圖中添加以下代碼:
@MVC4多語言IHttpModule實現.Lang命名空間

Home_Index生成的類名

TEST要國際化的字段




 



注意: 只有Home.Index.resx會生成一個叫Home_Index的類,其餘無類

而後添加以個實現了IHttpModule的類,暫且命名爲MyModule
此類須要實現2個方法
 public void Dispose() { } 便可
 public void Init(HttpApplication context)方法

 

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; } } } 
View Code

 

 

 而後添加路由 規則: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(); } } }
View Code

 

 
  RouteConfig.RegisterRoutes(RouteTable.Routes);//在此方法中添加路由規則
 
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 } ); } } }
View Code

 

 
而後在配置文件中聲明:
在web.config下的system.web下
<configuration>
    <system.web>
        <httpModules> 
            <add name="MyModule" type="MyModule"/> 
        </httpModules> 
    </system.web>
</configuration>
事踐顯示這種聲明註冊方法在IIS7.0下,即win7下是不work的。
必須按以下聲明:
<configuration> 
    <system.webServer> 
        <modules> 
            <add name="MyModule" type="MyModule"/> 
        </modules>   
    </system.webServer>
</configuration>
參考 : http://msdn.microsoft.com/zh-cn/library/ms227673

完成後具體請參照下圖: 

 
 
 
運行後如圖:








示例下載地址:百度網盤  http://pan.baidu.com/s/1dDtNheT
相關文章
相關標籤/搜索