[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是一种声明式编 ...
随机推荐
- /etc/sysctl.conf 调优 & 优化Linux内核参数
from: http://apps.hi.baidu.com/share/detail/15652067 http://keyknight.blog.163.com/blog/static/36637 ...
- python模块分析之time和datetime模块
前言 我们使用time和datetime模块的主要目的是对时间戳.时间字符串.时间元组等时间的表述对象进行相互的转化.而我们平时编码涉及两个时间:一个是上海时间,也可以说是北京时间,一个是UTC时间, ...
- PyCharm 2018实现远程调试代码
pycharm是一个非常强大的python开发工具,现在很多代码最终在线上跑的环境都是linux,而开发环境可能还是windows下开发,这就需要经常在linux上进行调试,或者在linux对代码进行 ...
- 公司软raid问题
RAID的技术介绍: stripe width(条带宽度):RAID中的磁盘数,就是组成这个stripe的磁盘数.如,4个磁盘组成的RAID 0,条带宽度就是4. stripe depth(条带深度) ...
- Nginx基本配置文件
Nginx基本配置文件 1. 基本配置文件 /etc/nginx/nginx.conf # nginx运行的用户 user nginx; # nginx进程数,建议设置为等于CPU总核心数. work ...
- navicate连接Linux下mysql慢,卡,以及mysql相关查询,授权
方法,网上的办法是在my.ini的“[mysqld]”下面加入一行“skip-name-resolve”,就像这样: 然后保存并重启mysql服务即可. service mysqld restart ...
- .NetCore使用Swagger进行单版本或多版本控制处理
前面已经介绍过了Swagger的基础使用了 下面继续分别详细说明下 不添加版本控制以及添加版本控制的使用情况,其实也基本一致,对看起来可能更加容易理解 第一步 导入nuget包 nuget导入Swas ...
- HTML布局思路
1.DIV+CSS布局 (1)按照由上到下,由里到外的方式 (2)样式由CSS去改变 代码: <style type="text/css"> * { margin:0p ...
- API的防重
说说API的防重放机制 2017-03-20 18:19 by 轩脉刃, 685 阅读, 7 评论, 收藏, 编辑 说说API的防重放机制 我们在设计接口的时候,最怕一个接口被用户截取用于重放攻击.重 ...
- kebab HDU2883
题意:现在有n个人要烤肉,有m个烤肉架,然后给出每个人的烤肉开始时间si,结束时间ei,以及要烤肉的串数num,还有拷一串的时间ti,然后问你能不能满足所有人的要求. 为3572的进阶题 每个人为一个 ...