• 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类的具体实现:

     
    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
     

     然后添加路由 规则:

     
    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
  • 相关阅读:
    软工实践总结
    Beta总结
    beta冲刺6/7
    beta冲刺5/7
    Beta冲刺4/7
    beta冲刺3/7
    beta冲刺2/7
    beta冲刺1/7
    答辩总结
    ES6中的块级作用域与函数声明
  • 原文地址:https://www.cnblogs.com/unintersky/p/3969612.html
Copyright © 2020-2023  润新知