摘要

在实际项目中,经常遇到,开发的项目要提供给不同的国家使用,如果根据国家来开发不同的站点,肯定是非常耗时又耗成本的。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]国际化的更多相关文章

  1. ASP.NET MVC之国际化(十一)

    前言 在项目中遇到国际化语言的问题是常有的事情,之前在做关于MVC国际化语言时,刚开始打算全部利用AngularJS来实现,但是渐渐发现对于页面Title难以去控制其语言转换,于是对于页面Tiltle ...

  2. ASP.NET MVC Filters 4种默认过滤器的使用【附示例】

    过滤器(Filters)的出现使得我们可以在ASP.NET MVC程序里更好的控制浏览器请求过来的URL,不是每个请求都会响应内容,只响应特定内容给那些有特定权限的用户,过滤器理论上有以下功能: 判断 ...

  3. Datatables 在asp.net mvc中的使用

    前言 最近使用ABP(ASP.NET Boilerplate)做新项目,以前都是自己扩展一个HtmlHelper来完成同步/异步分页,但是有个地方一直不满意,排序太费劲. 以前接触过一点点的Datat ...

  4. ASP.NET MVC 监控诊断、本地化和缓存

    这篇博客主要是针对asp.net mvc项目的一些常用的东东做一个讲解,他们分别是监控诊断.本地化和缓存.虽然前两者跟asp.net mvc看上去好像是没什么关联. 但其实如果真正需要做asp.net ...

  5. [渣译文] 使用 MVC 5 的 EF6 Code First 入门 系列:为ASP.NET MVC应用程序创建更复杂的数据模型

    这是微软官方教程Getting Started with Entity Framework 6 Code First using MVC 5 系列的翻译,这里是第六篇:为ASP.NET MVC应用程序 ...

  6. 【MVC5】ASP.NET MVC 项目笔记汇总

    ASP.NET MVC 5 + EntityFramework 6 + MySql 先写下列表,之后慢慢补上~ 对MySql数据库使用EntityFramework 使用域用户登录+记住我 画面多按钮 ...

  7. asp.net mvc开发的社区产品相关开发文档分享

    分享一款基于asp.net mvc框架开发的社区产品--近乎.目前可以在官网免费下载,下载地址:http://www.jinhusns.com/Products/Download?type=whp 1 ...

  8. ASP.NET MVC 第六回 过滤器Filter

    在Asp.netMvc中当你有以下及类似以下需求时你可以使用Filter功能 判断登录与否或用户权限 决策输出缓存 防盗链 防蜘蛛 本地化与国际化设置 实现动态Action Filter是一种声明式编 ...

  9. ASP.NET MVC 过滤器Filter

    在Asp.netMvc中当你有以下及类似以下需求时你可以使用Filter功能 判断登录与否或用户权限 决策输出缓存 防盗链 防蜘蛛 本地化与国际化设置 实现动态Action Filter是一种声明式编 ...

随机推荐

  1. hibernate的一对多和多对一关联

    一对一的关联就不写了,一般项目也用不到,如果可以一对一就直接合成一个表了,也不会出现一对一的关系. 本文主要研究一对多的关系. 1.一对多的关系研究: (1)RDB中关系表达:  多的一方创建外键指向 ...

  2. 【Alsa】播放声音和录音详细流程

    linux中,无论是oss还是alsa体系,录音和放音的数据流必须分析清楚.先分析alsa驱动层,然后关联到alsa库层和应用层. 二,链接分析: 1)链路一 usr/src/linux-source ...

  3. Ansible Tower系列 三(使用tower执行一个任务)【转】

    创建playbook Tower playbook 项目默认存在 /var/lib/awx/projects/ su - awx cd projects/ mkdir ansible-for-devo ...

  4. [转]MongoDB更新操作replaceOne()实例讲解

    最近正在学习MongoDB,作为数据库的学习当然是要从CRUD开始学起了.这篇文章默认读者是知道如何安装MongoDB.如何运行MongoDB实例以及了解了MongoDB中的collection.do ...

  5. AC自动机学习笔记-1(怎么造一台AC自动机?)

    月更博主又来送温暖啦QwQ 今天我们学习的算法是AC自动机.AC自动机是解决字符串多模匹配问题的利器,而且代码也十分好打=w= 在这一篇博客里,我将讲解AC自动机是什么,以及怎么构建一个最朴素的AC自 ...

  6. maven中的各种问题

    [ERROR] Plugin org.apache.maven.plugins:maven-shade-plugin:3.1 or one of its dependencies could not ...

  7. Redis整体

    介绍 Redis是一个开源的高性能的key-value存储系统.具有以下特点: 1.Redis支持数据的持久化,可以将内存中的数据保持在磁盘中,重启的时候可以再次加载进行使用. 2.Redis不仅仅支 ...

  8. 003.NFS配置实例

    一 NFS常见服务管理 1.1 启动NFS [root@imxhy ~]# systemctl start nfs #CentOS7.x系列启动 [root@imxhy ~]# service nfs ...

  9. SpringMVC框架05——拦截器

    1.拦截器概述 Spring MVC的拦截器(Interceptor)与Java Servlet的过滤器(Filter)类似,它主要用于拦截用户的请求并做相应的处理,通常应用在权限验证.记录请求信息的 ...

  10. JedisConnectionException: java.net.ConnectException: Connection refused

    出现问题 我遇到的一个问题,在连接redis的时候出现了错误!错误如下: JedisConnectionException: java.net.ConnectException: Connection ...