ASP.NET MVC5多语言简单实现方案

功能

实现动态切换语言,Demo做了三种语言库可以切换,包括资源文件的定义,实体对象属性设置,后台代码Controller,IAuthorizationFilter,HtmlHelper的实现,做法简单易学,配合我之前发布的# MVC Scaffolding SmartCode-Engine 更新 模板中新增了多语言资源文件的生成功能,现在发现我的这个框架和目前很流行的ABP框架是类似更有点像收费版的Asp.net Zero,只是更加轻量级,更方便,更快速,唯一的不足就是无法升级到Asp.net Core因为在dotnet core下的Scaffolding这块扩展不像MVC5那么容易实现,这块还需要研究,下一步就准备升级到asp.net core.重新开发一套类似Asp.net Zero的代码生成插件.

Github download Demo

demo1.gif

具体实现方法

  1. 定义实体类
    通过Display属性定义Name ResourceType,需要读取的语言库资源文件

    image.png

  2. 生成资源文件
    通过mvc scaffolding扩展工具会自动生成对应实体对象的3个资源文件默认中文,繁体,英文
    繁体需要自己翻译,英文内容根据字段名定义后已大写字母分割 DateTime 现实 Date Time

    image.png

    页面功能按钮语言资源文件库
    image.png

    image.png

  3. 前后端代码实现语言切换功能
    -选择切换语言

    image.png

    JS代码

/* multiple lang dropdown */
$('#dropdownlang-dropdown-menu').on('click', 'a', function () {
  const lang = this.text;
  const flag = this.firstElementChild.className;
  const culture = this.firstElementChild.getAttribute("culture");
  $('#dropdownlang').children()[0].className = flag;
  $('#dropdownlang').children()[1].innerHTML = lang;
  localStorage.setItem('lang-text', lang);
  localStorage.setItem('lang-css', flag);
  localStorage.setItem('lang-culture', culture);
  $.get('/Account/SetCulture?lang=' + culture).then(res => {
    if (res.success) {
      location.reload();
    }

  });
});
$(function () {
  const lang = localStorage.getItem('lang-text');
  const css = localStorage.getItem('lang-css');
  const culture = localStorage.getItem('lang-culture');
    scripttag = document.createElement("script");
    scripttag.type = "text/javascript";
    scripttag.src = src;
    document.body.appendChild(scripttag);
    $.parser.parse();
 
 
  };
  if (lang && css && culture) {
    $('#dropdownlang').children()[0].className = css;
    $('#dropdownlang').children()[1].innerHTML = lang;

  }
});

后端代码

[HttpGet]
    public ActionResult SetCulture(string lang) {
      //这里设置CultureInfo是多余的
      switch (lang.Trim())
      {
        case "en":
          CultureInfo.CurrentCulture = new CultureInfo("en-US");
          CultureInfo.CurrentUICulture = new CultureInfo("en-US");
          break;
        case "cn":
          CultureInfo.CurrentCulture = new CultureInfo("zh-CN");
          CultureInfo.CurrentUICulture = new CultureInfo("zh-CN");
          break;
        case "tw":
          CultureInfo.CurrentCulture = new CultureInfo("zh-TW");
          CultureInfo.CurrentUICulture = new CultureInfo("zh-TW");
          break;
      }
     //这里设置CultureInfo是多余的
      var cookie = new HttpCookie("culture", lang)
      {
        Expires = DateTime.Now.AddYears(1)
      };
      Response.Cookies.Add(cookie);
      return Json(new { success = true }, JsonRequestBehavior.AllowGet);

    }

CultureFilter 这是关键 这是没有使用RouteData,通过修改url来保存当前语言要改的地方很多还要修改路由规则,所以我就用Cookies来保存

public class CultureFilter : IAuthorizationFilter
  {
    private readonly string defaultCulture;

    public CultureFilter()
    {
      this.defaultCulture = "cn";
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
      var culture = filterContext.HttpContext.Request.Cookies["culture"];
      var lang = defaultCulture;
      if (culture != null && culture.Value != null)
      {
        lang = culture.Value;
        filterContext.HttpContext.Response.Cookies.Set(culture);
      }
      switch (lang.Trim())
      {
        case "en":
          CultureInfo.CurrentCulture = new CultureInfo("en-US");
          CultureInfo.CurrentUICulture = new CultureInfo("en-US");
          //Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
          //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
          break;
        case "cn":
          CultureInfo.CurrentCulture = new CultureInfo("zh-CN");
          CultureInfo.CurrentUICulture = new CultureInfo("zh-CN");
          //Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-CN");
          //Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN");
          break;
        case "tw":
          CultureInfo.CurrentCulture = new CultureInfo("zh-TW");
          CultureInfo.CurrentUICulture = new CultureInfo("zh-TW");
          //Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-TW");
          //Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-TW");
          break;
      }
    }
  }

HtmlHelper 代码实现语言的输出

    /// 
    /// 多语言切换
    /// 
    /// 
    /// 
    /// 
    public static HtmlString L(this HtmlHelper helper, string name) {

      var resource = new System.Resources.ResourceManager(typeof(WebApp.resource.Global));
      var text = resource.GetString(name);
      return new HtmlString(text ?? name);
    }
    /// 
    /// 前端easyui或是其它js相关的比如提示信息也需要转换必须在这里加载不同的语言文件
    /// 
    public static HtmlString LangScriptTag(this HtmlHelper helper,string defaultsrc) {
      var src = defaultsrc;
      var lang = CultureInfo.CurrentCulture.Name;
      switch (lang)
      {
        case "en-US":
          src = "/Scripts/easyui/locale/easyui-lang-en.js";
          break;
        case "zh-CN":
          src = "/Scripts/easyui/locale/easyui-lang-zh_CN.js";
          break;
        case "zh-TW":
          src = "/Scripts/easyui/locale/easyui-lang-zh_TW.js";
          break;
        default:
          src = defaultsrc;
          break;
      }
      return new HtmlString($"");
    }

//html代码

你可能感兴趣的:(ASP.NET MVC5多语言简单实现方案)