[Asp.net mvc]国际化
摘要
在实际项目中,经常遇到,开发的项目要提供给不同的国家使用,如果根据国家来开发不同的站点,肯定是非常耗时又耗成本的。asp.net中,提供了一种比较方便的方式,可以使用资源文件的方式,使我们的站点,面向国际化。
一个例子
新建一个mvc项目,如下:
其中文件夹App_GlobalResources,为资源文件文件夹。可以通过右键添加,如图:
Languages.resx:默认中文资源文件。
Languages.en.resx:英文资源文件。
资源项包括
注意,添加过之后,你可以对比一下,这两个文件,其中默认中文资源文件Languages.Designer.cs中有代码,英文资源的是没有代码的(这里不再做分析,之后可以通过反编译工具进行查看)。
测试
为了测试方便,添加一个UserInfo的实体类
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Wolfy.Lang.Models
{
/// <summary>
/// 默认 资源文件 中文
/// </summary>
public class UserInfo
{ [Display(Name = "Id", ResourceType = typeof(Resources.Languages))]
public int Id { set; get; }
[Display(Name = "Name", ResourceType = typeof(Resources.Languages))]
public string Name { set; get; }
[Display(Name = "Gender", ResourceType = typeof(Resources.Languages))]
public string Gender { set; get; }
[Display(Name = "Age", ResourceType = typeof(Resources.Languages))]
public int Age { set; get; }
}
}
这里采用默认资源中文的资源文件。
获取语言的辅助类,用来获取语言。这里为了设置方便,采用获取cookie中的lang字段作为测试用,当然你也可以使用url进行传递。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Wolfy.Lang.Utilities
{
public class LanguageHelper
{
private static List<string> _cultures = new List<string> { "zh-CN", "en-US" };
public static string FindLanguageName(string name)
{
if (string.IsNullOrEmpty(name))
{
return _cultures[];
}
if (_cultures.Where(l => l.Equals(name, StringComparison.InvariantCultureIgnoreCase)).Any())
{
return name;
}
var partName = GetPartName(name);
foreach (var item in _cultures)
{
if (item.StartsWith(partName))
{
return item;
}
}
return _cultures[];
}
private static string GetPartName(string name)
{
if (!name.Contains("-"))
{
return name;
}
else
{
return name.Split('-')[];
}
}
}
}
添加BaseController,在需要国际化的视图对应的控制器,都需要继承该类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using Wolfy.Lang.Utilities; namespace Wolfy.Lang.Controllers
{
public class BaseController : Controller
{
protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
string langName = string.Empty;
HttpCookie langCookie = Request.Cookies["lang"];
if (langCookie != null)
{
langName = langCookie.Value;
}
else
{
langName = Request.UserLanguages != null && Request.UserLanguages.Length > ? Request.UserLanguages[] : string.Empty;
}
langName = LanguageHelper.FindLanguageName(langName);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(langName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
return base.BeginExecuteCore(callback, state);
}
}
}
添加user控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc; namespace Wolfy.Lang.Controllers
{
public class UserController : BaseController
{
// GET: User
public ActionResult Index()
{
ViewBag.submit = Resources.Languages.Submit;
HttpCookie cookie = Request.Cookies["lang"];
if (cookie == null)
{
//默认中文
cookie = new HttpCookie("lang", "zh") { Expires = DateTime.Now.AddDays() };
Response.Cookies.Add(cookie);
}
return View();
}
}
}
对应的视图
@model Wolfy.Lang.Models.UserInfo @{
Layout = null;
var culture = System.Threading.Thread.CurrentThread.CurrentCulture.Name.ToLowerInvariant();
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval") @using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal"> @Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10"> @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="@ViewBag.submit" class="btn btn-default" />
</div>
</div>
</div>
} <div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
测试
通过切换cookie中lang的值进行语言的切换
切换英文
修改cookie中lang字段对应的值为en-US
总结
之前,国际化都是通过angularjs的方式在前端实现的,今天尝试下mvc中的实现方式。这里需要注意的,在使用特性Display的ResourceType参数时,需要指定Languages是public的,默认是interval,需要修改可访问性。
[Asp.net mvc]国际化的更多相关文章
- ASP.NET MVC之国际化(十一)
前言 在项目中遇到国际化语言的问题是常有的事情,之前在做关于MVC国际化语言时,刚开始打算全部利用AngularJS来实现,但是渐渐发现对于页面Title难以去控制其语言转换,于是对于页面Tiltle ...
- ASP.NET MVC Filters 4种默认过滤器的使用【附示例】
过滤器(Filters)的出现使得我们可以在ASP.NET MVC程序里更好的控制浏览器请求过来的URL,不是每个请求都会响应内容,只响应特定内容给那些有特定权限的用户,过滤器理论上有以下功能: 判断 ...
- Datatables 在asp.net mvc中的使用
前言 最近使用ABP(ASP.NET Boilerplate)做新项目,以前都是自己扩展一个HtmlHelper来完成同步/异步分页,但是有个地方一直不满意,排序太费劲. 以前接触过一点点的Datat ...
- ASP.NET MVC 监控诊断、本地化和缓存
这篇博客主要是针对asp.net mvc项目的一些常用的东东做一个讲解,他们分别是监控诊断.本地化和缓存.虽然前两者跟asp.net mvc看上去好像是没什么关联. 但其实如果真正需要做asp.net ...
- [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:为ASP.NET MVC应用程序创建更复杂的数据模型
这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第六篇:为ASP.NET MVC应用程序 ...
- 【MVC5】ASP.NET MVC 项目笔记汇总
ASP.NET MVC 5 + EntityFramework 6 + MySql 先写下列表,之后慢慢补上~ 对MySql数据库使用EntityFramework 使用域用户登录+记住我 画面多按钮 ...
- asp.net mvc开发的社区产品相关开发文档分享
分享一款基于asp.net mvc框架开发的社区产品--近乎.目前可以在官网免费下载,下载地址:http://www.jinhusns.com/Products/Download?type=whp 1 ...
- ASP.NET MVC 第六回 过滤器Filter
在Asp.netMvc中当你有以下及类似以下需求时你可以使用Filter功能 判断登录与否或用户权限 决策输出缓存 防盗链 防蜘蛛 本地化与国际化设置 实现动态Action Filter是一种声明式编 ...
- ASP.NET MVC 过滤器Filter
在Asp.netMvc中当你有以下及类似以下需求时你可以使用Filter功能 判断登录与否或用户权限 决策输出缓存 防盗链 防蜘蛛 本地化与国际化设置 实现动态Action Filter是一种声明式编 ...
随机推荐
- python中的*号
from:https://www.douban.com/note/231603832/ 传递实参和定义形参(所谓实参就是调用函数时传入的参数,形参则是定义函数是定义的参数)的时候,你还可以使用两个特殊 ...
- eclipse安装阿里巴巴java开发规范插件
阿里巴巴java开发规范插件 作为JAVA开发人员,始终没有一个明确的规范,何为好代码,何为坏代码,造成不同人的代码风格不同,接手别人代码后改造起来相当困难.前不久,阿里巴巴发布了<阿里巴巴Ja ...
- makefile 中 foreach
四.foreach 函数 foreach函数和别的函数非常的不一样.因为这个函数是用来做循环用的,Makefile中的foreach函数几乎是仿照于Unix标准Shell(/bin/sh)中的for语 ...
- poj1292
prim,把每个墙看成一个节点,从起点用prim求最小生成树,直到覆盖到终点为止,输出最小生成树中的最大边 #include <cstdio> #include <cmath> ...
- CSS font-family 字体介绍,\5b8b\4f53 表示“宋体”
font-family采用一种"回退"的形式来保存字体,可以写若干种字体.当第一种字体浏览器不支持的时候,会找第二种字体,一次类推. font-family字体分为两类: 特殊字体 ...
- Java编程的逻辑 (18) - 为什么说继承是把双刃剑
本系列文章经补充和完善,已修订整理成书<Java编程的逻辑>,由机械工业出版社华章分社出版,于2018年1月上市热销,读者好评如潮!各大网店和书店有售,欢迎购买,京东自营链接:http: ...
- shell编程快速入门及实战
shell编程:对于hadoop程序员,通常需要熟悉shell编程,因为shell可以非常方便的运行程序代码. 1.shell文件格式:xxx.sh #!/bin/sh ---shell文件第一行必须 ...
- ps -aux与ps -ef
ps -aux与ps -ef这两个命令显示的结果是差不多的. 不同之处就是显示风格不同,前者是BSD风格,后者SYSTEM V(其实我不太明白这尼玛风格是什么跟什么,我看起来都差不多啊) 然后重要的不 ...
- java 常用面试题
基础问题和思想:1.抽象类和接口的区别(单纯的语法区别只能给一半分,要说出来适用场景):2.hashcode()和equals()的关系:3.HashMap(Set)底层机制(用到的数据结构以及代码原 ...
- vue播放video插件vue-video-player实现hls, rtmp播放全过程
1.安装插件 1 npm install vue-video-player -S 2.配置插件 在main.js里添加 1 import VideoPlayer from 'vue-video-pla ...