ASP.NET(3):多語言實現

來源:互聯網
上載者:User

1.定義使用者語言設定資訊類,對使用者選擇的語言進行儲存,可以用Session,這裡選用的是Cookies.

 

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CommonUtility;

/**//// <summary>
///ASPNET方式下為上下文語言環境提供語言設定對象
/// </summary>
public class ASPNETLocalizer : ILocalizer
{
    HttpContext httpContext;
    /**//// <summary>
    /// 建立對象
    /// </summary>
    /// <param name="httpResponse">HTTP相應對象</param>
    public ASPNETLocalizer()
    {
        this.httpContext = HttpContext.Current;
    }

    ILocalizer 成員#region ILocalizer 成員

    public string LocalizerName
    {
        get
        {
            //由於Cookies有Response.Request之分,所以需要在HttpContext上下文中儲存語言資訊
            if (httpContext.Items[CookiesCenter.Language] == null)
            {
                var localizerName = Cookies.ReadCookies(httpContext.Request, CookiesCenter.Language);
                if (String.IsNullOrEmpty(localizerName))
                {
                    localizerName = "zh-CN";
                    SetName(localizerName);
                }
                return localizerName;
            }
            else
            {
                return httpContext.Items[CookiesCenter.Language].ToString();
            }
        }
        set
        {
            SetName(value);
        }
    }

    /**//// <summary>
    /// 設定名稱
    /// </summary>
    /// <param name="localizerName">語言名稱</param>
    void SetName(string localizerName)
    {
        Cookies.WriteCookies(httpContext.Response, CookiesCenter.Language, localizerName);
        httpContext.Items[CookiesCenter.Language] = localizerName;
        System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(localizerName);
        System.Threading.Thread.CurrentThread.CurrentCulture = ci;
        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    }

    #endregion
}

由於對Cookies的訪問有一定的限制,Request對象時候讀,Response對象寫,所以我們需要將使用者選擇語言的值儲存在其它對象裡面,可以儲存在Session裡,這裡選擇儲存在HttpContext.Items中。

2.定義HttpModule,每次訪問的時候根據使用者的設定來改變語言

 

Code
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using CommonUtility;

/// <summary>
///自訂向實作類別提供模組初始化和處置事件。
/// </summary>
public class MYHttpModule : IHttpModule
{
    HttpApplication context;
    public PhenixHttpModule()
    {
     
    }

    #region IHttpModule 成員

    public void Dispose()
    {
        UnityContainer.ObjectProvider = null;
        context.PostAcquireRequestState -= new EventHandler(context_PostAcquireRequestState);
        
    }

    public void Init(HttpApplication context)
    {
        this.context = context; 
        context.PostAcquireRequestState += new EventHandler(context_PostAcquireRequestState);
    }

    void context_PostAcquireRequestState(object sender, EventArgs e)
    {
        var app = sender as HttpApplication;

        if (UnityContainer.ObjectProvider == null)
        {
            var provider = new ASPNETObjectProvider();
            UnityContainer.ObjectProvider = provider;
        }

        System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(UnityContainer.GetObject<ILocalizer>().LocalizerName);
        System.Threading.Thread.CurrentThread.CurrentCulture = ci;
        System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
    }

    #endregion
}

 

3.在Web.Config中添加記錄

 

<httpModules>
      <add name="MYModule" type="MYHttpModule"/>
</httpModules>

 

4.定義資源檔存取對象ResourceManager

 

Code
public class ResourceManager
{
    XElement ResourceManager;
    public Localizer()
    {
       //可以根據自己的需要處理資源檔的讀取
        var culture = System.Threading.Thread.CurrentThread.CurrentCulture;

        var filepath = HttpContext.Current.Server.MapPath("~/App_Code/"+ culture.Name+"/lang.xml");
        xmlLocalizer = XElement.Load(filepath);
    }

    public Localizer()
        : this())
    {
    }

    public string GetString(string id)
    {
         return return xmlLocalizer.Descendants("resource").Where(p => p.Attribute("name").Value == id).Select(p1 => p1.Value).FirstOrDefault();
    }
}

 

5.在需要賦值的地方,執行個體化賦值即可

 

說明:初學ASP.NET,此方案很不成熟,自己練手用。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.