实现MVC.NET 5的国际化
阅读原文时间:2023年07月15日阅读:1

实现国际化有三种做法:

  1. 创建资源文件。
  2. 每种语言设置一套单独的View。
  3. 1 + 2。

通常而言,第一种方法的可维护性是最高的。因为随着项目的规模的扩大,为每种语言设置一套单独的View,前期的工作量和后期的维护成本都会太高。

但是如果只采用资源文件的做法,在某些场合下,View的显示会出现问题,诸如一些文字次序是从右到左显示的语言,很显然仅仅更换文字内容也是不合适的。

所以,最终采取何种方式还是要看具体的项目情况而定。接下去的内容只针对第一种做法。

概括起来,有如下步骤:

  1. 创建资源文件
  2. Controller中添加国际化的支持
  3. 配置View

============ Action Now! ============

1. 创建资源文件

1) 不要将资源文件添加到现有的项目中,而是新建一个Class Library的项目, 这样可以在日后复用此资源文件到其它项目中。

2) 创建资源文件。资源文件名可以自由定义,在这里我创建一个名为Resources.resx的资源文件,做为默认的资源文件,通常用于英文。然后再定义一个Resources.zh-CN.resx的资源文件,用于中文。在这里我们可以看出资源文件定义的规律,即Resources.[编码名].resx。创建结果如下:

2. Controller中添加国际化的支持

1) 创建BaseController文件,做为所有Controller的父类。

 public class BaseController : Controller

 {

     protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)

     {

         string cultureName = null;

         // Attempt to read the culture cookie from Request

         HttpCookie cultureCookie = Request.Cookies\["\_culture"\];

         if (cultureCookie != null)

             cultureName = cultureCookie.Value;

         else

             cultureName = Request.UserLanguages != null && Request.UserLanguages.Length >  ?

                     Request.UserLanguages\[\] :  // obtain it from HTTP header AcceptLanguages

                     null;

         // Validate culture name

         cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe

         // Modify current thread's cultures           

         Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);

         Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

         return base.BeginExecuteCore(callback, state);

     }

}

2) 将每个Controller的父类改为BaseController。

3) 可选。实现设置语言Cookie的方法,这样用户就可以通过自定义语言,而不是只能依赖浏览器的默认语言。

     public ActionResult SetCulture(string culture)

     {

         // Validate input

         culture = CultureHelper.GetImplementedCulture(culture);

         // Save culture in a cookie

         HttpCookie cookie = Request.Cookies\["\_culture"\];

         if (cookie != null)

             cookie.Value = culture;   // update cookie value

         else

         {

             cookie = new HttpCookie("\_culture");

             cookie.Value = culture;

             cookie.Expires = DateTime.Now.AddYears();

         }

         Response.Cookies.Add(cookie);

         return RedirectToAction("Index");

     } 

 4) 创建CultureHelper.cs。

 public static class CultureHelper

 {

     // Valid cultures

     private static readonly List<string> \_validCultures = new List<string> { "af", "af-ZA", "sq", "sq-AL", "gsw-FR", "am-ET", "ar", "ar-DZ", "ar-BH", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-AE", "ar-YE", "hy", "hy-AM", "as-IN", "az", "az-Cyrl-AZ", "az-Latn-AZ", "ba-RU", "eu", "eu-ES", "be", "be-BY", "bn-BD", "bn-IN", "bs-Cyrl-BA", "bs-Latn-BA", "br-FR", "bg", "bg-BG", "ca", "ca-ES", "zh-HK", "zh-MO", "zh-CN", "zh-Hans", "zh-SG", "zh-TW", "zh-Hant", "co-FR", "hr", "hr-HR", "hr-BA", "cs", "cs-CZ", "da", "da-DK", "prs-AF", "div", "div-MV", "nl", "nl-BE", "nl-NL", "en", "en-AU", "en-BZ", "en-CA", "en-029", "en-IN", "en-IE", "en-JM", "en-MY", "en-NZ", "en-PH", "en-SG", "en-ZA", "en-TT", "en-GB", "en-US", "en-ZW", "et", "et-EE", "fo", "fo-FO", "fil-PH", "fi", "fi-FI", "fr", "fr-BE", "fr-CA", "fr-FR", "fr-LU", "fr-MC", "fr-CH", "fy-NL", "gl", "gl-ES", "ka", "ka-GE", "de", "de-AT", "de-DE", "de-LI", "de-LU", "de-CH", "el", "el-GR", "kl-GL", "gu", "gu-IN", "ha-Latn-NG", "he", "he-IL", "hi", "hi-IN", "hu", "hu-HU", "is", "is-IS", "ig-NG", "id", "id-ID", "iu-Latn-CA", "iu-Cans-CA", "ga-IE", "xh-ZA", "zu-ZA", "it", "it-IT", "it-CH", "ja", "ja-JP", "kn", "kn-IN", "kk", "kk-KZ", "km-KH", "qut-GT", "rw-RW", "sw", "sw-KE", "kok", "kok-IN", "ko", "ko-KR", "ky", "ky-KG", "lo-LA", "lv", "lv-LV", "lt", "lt-LT", "wee-DE", "lb-LU", "mk", "mk-MK", "ms", "ms-BN", "ms-MY", "ml-IN", "mt-MT", "mi-NZ", "arn-CL", "mr", "mr-IN", "moh-CA", "mn", "mn-MN", "mn-Mong-CN", "ne-NP", "no", "nb-NO", "nn-NO", "oc-FR", "or-IN", "ps-AF", "fa", "fa-IR", "pl", "pl-PL", "pt", "pt-BR", "pt-PT", "pa", "pa-IN", "quz-BO", "quz-EC", "quz-PE", "ro", "ro-RO", "rm-CH", "ru", "ru-RU", "smn-FI", "smj-NO", "smj-SE", "se-FI", "se-NO", "se-SE", "sms-FI", "sma-NO", "sma-SE", "sa", "sa-IN", "sr", "sr-Cyrl-BA", "sr-Cyrl-SP", "sr-Latn-BA", "sr-Latn-SP", "nso-ZA", "tn-ZA", "si-LK", "sk", "sk-SK", "sl", "sl-SI", "es", "es-AR", "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-SV", "es-GT", "es-HN", "es-MX", "es-NI", "es-PA", "es-PY", "es-PE", "es-PR", "es-ES", "es-US", "es-UY", "es-VE", "sv", "sv-FI", "sv-SE", "syr", "syr-SY", "tg-Cyrl-TJ", "tzm-Latn-DZ", "ta", "ta-IN", "tt", "tt-RU", "te", "te-IN", "th", "th-TH", "bo-CN", "tr", "tr-TR", "tk-TM", "ug-CN", "uk", "uk-UA", "wen-DE", "ur", "ur-PK", "uz", "uz-Cyrl-UZ", "uz-Latn-UZ", "vi", "vi-VN", "cy-GB", "wo-SN", "sah-RU", "ii-CN", "yo-NG" };

     // Include ONLY cultures you are implementing

     private static readonly List<string> \_cultures = new List<string> {

         "zh-CN",

         "en-US",

     };

     /// <summary>

     /// Returns true if the language is a right-to-left language. Otherwise, false.

     /// </summary>

     public static bool IsRighToLeft()

     {

         return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.IsRightToLeft;

     }

     /// <summary>

     /// Returns a valid culture name based on "name" parameter. If "name" is not valid, it returns the default culture "en-US"

     /// </summary>

     /// <param name="name" />Culture's name (e.g. en-US)</param>

     public static string GetImplementedCulture(string name)

     {

         // make sure it's not null

         if (string.IsNullOrEmpty(name))

             return GetDefaultCulture(); // return Default culture

         // make sure it is a valid culture first

         if (\_validCultures.Where(c => c.Equals(name, StringComparison.InvariantCultureIgnoreCase)).Count() == )

             return GetDefaultCulture(); // return Default culture if it is invalid

         // if it is implemented, accept it

         if (\_cultures.Where(c => c.Equals(name, StringComparison.InvariantCultureIgnoreCase)).Count() > )

             return name; // accept it

         // Find a close match. For example, if you have "en-US" defined and the user requests "en-GB",

         // the function will return closes match that is "en-US" because at least the language is the same (ie English) 

         var n = GetNeutralCulture(name);

         foreach (var c in \_cultures)

             if (c.StartsWith(n))

                 return c;

         // else

         // It is not implemented

         return GetDefaultCulture(); // return Default culture as no match found

     }

     /// <summary>

     /// Returns default culture name which is the first name decalared (e.g. en-US)

     /// </summary>

     /// <returns></returns>

     public static string GetDefaultCulture()

     {

         return \_cultures\[\]; // return Default culture

     }

     public static string GetCurrentCulture()

     {

         return Thread.CurrentThread.CurrentCulture.Name;

     }

     public static string GetCurrentNeutralCulture()

     {

         return GetNeutralCulture(Thread.CurrentThread.CurrentCulture.Name);

     }

     public static string GetNeutralCulture(string name)

     {

         if (name.Length < )

             return name;

         return name.Substring(, ); // Read first two chars only. E.g. "en", "es"

     }

}

注意_cultures数组里的是当前系统支持的语言。

3. 配置View

1) 在MVC项目中添加对Resources项目的引用。

2) 修改View目录下的web.config文件,在pages下添加namespace=Resources。这样在View中就能够直接引用Resources。

 <pages pageBaseType="System.Web.Mvc.WebViewPage">

   <namespaces>

     <add namespace="System.Web.Mvc" />

     <add namespace="System.Web.Mvc.Ajax" />

     <add namespace="System.Web.Mvc.Html" />

     <add namespace="System.Web.Optimization"/>

     <add namespace="System.Web.Routing" />

     <add namespace="Resources" />

   </namespaces>

 </pages>

3)       在View中需要的地方写@Resources.[key]。例如:

@Resources.ApplicationName

@Resources.Expose

完工。本文忽略了设置语言的前端实现,和后台的资源文件内容的提取。如果有想要知道的朋友,可以提出来,我会另外再写一篇做介绍。

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章