代码改变世界

.NET 中从一个类库中访问资源文件,以实现 ASP.NET 或 ASP.NET MVC 的国际化

2012-05-23 22:39  音乐让我说  阅读(417)  评论(0编辑  收藏  举报

直接贴代码了:

项目解决方案图

资源文件图

代码如下:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .Title
        {
            text-align:center;
            font-size:24;
            font-family:Arial;   
       }
       
       .Author
       {
           text-align:center;
           font-size:16;
           font-family:Vrinda;  
       }
       
       .Content
       {
           text-align:center;
           font-size:20;
           font-family:MS UI Gothic;  
       }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="Title">
        <asp:Label ID="lbTitle" runat="server"></asp:Label>
    </div>
        <br />
    <div class="Author">
        <asp:Label ID="lbAuthor" runat="server" ></asp:Label>
    </div>
        <br />
    <div class="Content">
    <p>
        <%=strContent %>
    </p>
    <p><%=strLink %>: <a href="<%=strUrl %>"><%=strUrl %></a></p>
    </div>
<asp:DropDownList ID="ddlLanguage" runat="server" AutoPostBack="True" 
        onselectedindexchanged="ddlLanguage_SelectedIndexChanged">
        </asp:DropDownList>
    </form>
</body>
</html>

 

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Resources;
using System.Globalization;
using CSASPNETGloablizationInAssemblyResource;

namespace CSASPNETGloablizationInAssembly
{
    public partial class Default : System.Web.UI.Page
    {
        public string strContent = string.Empty;
        public string strUrl = string.Empty;
        public string strLink = string.Empty;
        const string strBaseName = "CSASPNETGloablizationInAssemblyResource.LanguageResource";

        ResourceManager manager = new ResourceManager(strBaseName, typeof(LanguageResource).Assembly);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CultureInfo culture = new CultureInfo(Context.Request.UserLanguages[0]);

                string strTitle = manager.GetString("Title", culture);
                string strAuthor = manager.GetString("Author", culture);
                this.strContent = manager.GetString("Content", culture);
                this.strUrl = manager.GetString("Url", culture);
                this.strLink = manager.GetString("Link", culture);
                lbTitle.Text = strTitle;
                lbAuthor.Text = strAuthor;
                bool flag = false;

                for (int i = 0; i < ddlLanguage.Items.Count; i++)
                {
                    if (ddlLanguage.Items[i].Value == culture.Name.ToLower())
                    {
                        flag = true;
                    }
                }
                if (flag)
                {
                    ddlLanguage.SelectedValue = culture.Name.ToLower();
                }
                else
                {
                    ddlLanguage.SelectedIndex = 0;
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ddlLanguage.Items.Add(new ListItem("United State", "en-us"));
            ddlLanguage.Items.Add(new ListItem("France", "fr-fr"));
            ddlLanguage.Items.Add(new ListItem("中国", "zh-cn"));
        }

        protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            string languageCode = ddlLanguage.SelectedValue;
            CultureInfo currentCulture = this.GetLanguageSpecifically(languageCode);
            lbTitle.Text = manager.GetString("Title", currentCulture);
            lbAuthor.Text = manager.GetString("Author", currentCulture);
            this.strContent = manager.GetString("Content", currentCulture);
            this.strLink = manager.GetString("Link", currentCulture);
            this.strUrl = manager.GetString("Url", currentCulture);
        }

        public CultureInfo GetLanguageSpecifically(string languageCode)
        {
            CultureInfo culture = new CultureInfo(languageCode);
            return culture;
        }
    }
}

 

 实战

1. MutilLanguageService.cs

    internal class MutilLanguageResult
    {
        public bool ResourceFileExists { get; set; }

        public bool ResourceKeyExists { get; set; }

        public string ReturnValueOnSuccess { get; set; }
    }

    /// <summary>
    /// 多语言服务
    /// </summary>
    public class MutilLanguageService
    {
        private const string ResNamePrefix = "web.MutilLanguage.CSharpResources.";

        /// <summary>
        /// 获取资源
        /// </summary>
        /// <param name="resName">比如:I.Ven.T_List_en-us</param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string TryGet(AccountInfo currentUserInfo, string parentResName, string key)
        {
            string fullResName = parentResName + currentUserInfo.TryGetResSubfix();
            //"web.MutilLanguage.CSharpResources.I.Ven.T_List_en-us"

            var result = TryGetCore(fullResName, key);
            if (result.ResourceFileExists && result.ResourceKeyExists && !string.IsNullOrEmpty(result.ReturnValueOnSuccess))
            {
                return result.ReturnValueOnSuccess;
            }
            if (!result.ResourceFileExists)
            {
                fullResName = parentResName + currentUserInfo.TryGetResSubfix_Underline();
                result = TryGetCore(fullResName, key);
                if (result.ResourceFileExists && result.ResourceKeyExists && !string.IsNullOrEmpty(result.ReturnValueOnSuccess))
                {
                    return result.ReturnValueOnSuccess;
                }
                if (!result.ResourceFileExists)
                {
                    return "Unknown resource file.";
                }
                if (!result.ResourceKeyExists)
                {
                    return string.Format("Unknown key:{0}", key);
                }
                return result.ReturnValueOnSuccess;
            }
            if (!result.ResourceKeyExists)
            {
                return string.Format("Unknown key:{0}", key);
            }
            return result.ReturnValueOnSuccess;
        }

        private static MutilLanguageResult TryGetCore(string fullResName, string key)
        {
            try
            {
                ResourceManager manager = new ResourceManager(ResNamePrefix + fullResName,
                    typeof(MutilLanguageService).Assembly);
                string value = manager.GetString(key);
                if (string.IsNullOrEmpty(value))
                {
                    return new MutilLanguageResult
                    {
                        ResourceFileExists = true,
                        ResourceKeyExists = false,
                        ReturnValueOnSuccess = null
                    };
                }
                return new MutilLanguageResult
                {
                    ResourceFileExists = true,
                    ResourceKeyExists = true,
                    ReturnValueOnSuccess = value
                };
            }
            catch (Exception)
            {
                return new MutilLanguageResult
                {
                    ResourceFileExists = false,
                    ResourceKeyExists = false,
                    ReturnValueOnSuccess = null
                };
            }
        }
    }

 

2. 定义 RazorViewPage 的基类

    public static class CommonLogicForViewPage
    {
        /// <summary>
        /// 获取资源名称的显示
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string T(HttpContextBase httpContext, string parentResName, string key)
        {
            AccountInfo currentUserInfo = FromPrincipalHelper.TryGetUserInfo(httpContext);
            return MutilLanguageService.TryGet(currentUserInfo, parentResName, key);
        }

        public static string GetMy97DatePickerLang(HttpContextBase httpContext)
        {
            AccountInfo currentUserInfo = FromPrincipalHelper.TryGetUserInfo(httpContext);
            if (currentUserInfo == null || string.IsNullOrEmpty(currentUserInfo.GS_LANG))
            {
                return string.Empty;
            }
            string tempLang = currentUserInfo.GS_LANG.Trim().ToUpper();
            switch (tempLang)
            {
                case "E":
                    return "en";
                case "T":
                    return "zh-tw";
                default:
                    return string.Empty;
            }
        }
    }

 

 

3. 泛型基类 和 非泛泛型基类

    public abstract class BaseViewPage : WebViewPage
    {
        public string ResName { get; set; }

        /// <summary>
        /// 获取资源名称的显示
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string T(string key)
        {
            return CommonLogicForViewPage.T(this.Context, this.ResName, key);
        }
    }

    public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
    {

        public string ResName { get; set; }

        /// <summary>
        /// 获取资源名称的显示
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string T(string key)
        {
            return CommonLogicForViewPage.T(this.Context, this.ResName, key);
        }
    }

 

4. 实际调用

@using web
@inherits web.BaseViewPage<WebdiyerPagedListWrapper<ins_snapshot_mas>>
@{
    this.ResName = "I.Ven.T_List";
    ViewBag.Title = T("Title");
    
}
<div class="label-span">
    @T("UserNameConditionName"):<input type="text" name="UserNameConditionName"/> 
</div>

 

 

谢谢浏览!