需求:有些网站需要多语言显示,比如简体中文,繁体中文,英文。

1、创建一个mvc项目:

2、创建App_GlobalResources

创建了中文、英文两个语言的资源文件,中文是程序的默认语言,所以我先创建Global.resx文件,然后是Global.en.resx,中间的“en”是英语的Culture Name。如果你需要法语,那么你只需要再创建Global.fr.resx文件,Visual Studio会自动生成对应的类。

3、创建一个过滤器:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc; namespace MultiMVCWebApp.Filters
{
public class LocalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{ if (filterContext.RouteData.Values["lang"] != null &&
!string.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString()))
{
///从路由数据(url)里设置语言
var lang = filterContext.RouteData.Values["lang"].ToString();
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
}
else
{
///从cookie里读取语言设置
var cookie = filterContext.HttpContext.Request.Cookies["ShaunXu.MvcLocalization.CurrentUICulture"];
var langHeader = string.Empty;
if (cookie != null)
{
///根据cookie设置语言
langHeader = cookie.Value;
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
}
else
{
///如果读取cookie失败则设置默认语言
langHeader = filterContext.HttpContext.Request.UserLanguages[];
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
}
///把语言值设置到路由值里
filterContext.RouteData.Values["lang"] = langHeader;
} /// 把设置保存进cookie
HttpCookie _cookie = new HttpCookie("ShaunXu.MvcLocalization.CurrentUICulture", Thread.CurrentThread.CurrentUICulture.Name);
_cookie.Expires = DateTime.Now.AddYears();
filterContext.HttpContext.Response.SetCookie(_cookie); base.OnActionExecuting(filterContext);
}
}
}

4、创建一个Controller:

using MultiMVCWebApp.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; namespace MultiMVCWebApp.Controllers
{
[Localization]
public class LangTestController : Controller
{
// GET: LangTest
public ActionResult Index()
{
ViewBag.Title = Resources.Gloable.Name;
ViewBag.Name = Resources.Gloable.Name;
ViewBag.Password = Resources.Gloable.Password;
return View();
}
}
}

5、配置路由:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing; namespace MultiMVCWebApp
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
"Localization", // 路由名称
"{lang}/{controller}/{action}/{id}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional }//参数默认值
); routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
); } }
}

6、视图View设置:

1)_Layout视图:

<!DOCTYPE html>

<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr") </head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink(@Resources.Gloable.AppName, "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink(@Resources.Gloable.Home, "Index", "Home")</li>
<li>@Html.ActionLink(@Resources.Gloable.About, "About", "Home")</li>
<li>@Html.ActionLink(@Resources.Gloable.Contact, "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div> @Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>

2)_LoginPartial视图:

@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right">
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink(@Resources.Gloable.Register, "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink(@Resources.Gloable.Login, "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}

3)LangTestController中的Index视图:

@{
ViewBag.Title = ViewBag.Title;
} @ViewBag.Title <br /> @ViewBag.Name <br /> @ViewBag.Password <br />

7、效果:

1)英文效果图,链接  http://localhost:10297/en/LangTest/Index

2)中文效果图,链接 http://localhost:10297/cn/LangTest/Index

asp.net mvc5 多语言应用的更多相关文章

  1. ASP.NET MVC5多语言切换快速实现方案

    功能 实现动态切换语言,Demo做了三种语言库可以切换,包括资源文件的定义,实体对象属性设置,后台代码Controller,IAuthorizationFilter,HtmlHelper的实现,做法比 ...

  2. ASP.NET MVC5入门2之Ajax实现数据查询

    开发环境:VS2013 数据库:SQL Server2008R2 架构:ASP.NET MVC5 开发语言:C# 代码下载链接:http://download.csdn.net/detail/u010 ...

  3. ASP.NET MVC5+EF6+EasyUI 后台管理系统(1)-前言与目录(持续更新中...)

    开发工具:VS2015(2012以上)+SQL2008R2以上数据库  您可以有偿获取一份最新源码联系QQ:729994997 价格 666RMB  升级后界面效果如下: 任务调度系统界面 http: ...

  4. ASP.NET MVC5学习笔记01

    由于之前在项目中也使用MVC进行开发,但是具体是那个版本就不是很清楚了,但是我觉得大体的思想是相同的,只是版本高的在版本低的基础上增加了一些更加方便操作的东西.下面是我学习ASP.NET MVC5高级 ...

  5. Linux(CentOS 6.5)下配置Mono和Jexus并且部署ASP.NET MVC5

    1.开篇说明 a. 首先我在写这篇博客之前,已经在自己本地配置了mono和jexus并且成功部署了asp.net mvc项目,我也是依赖于在网上查找的各种资料来配置环境并且部署项目的,而其在网上也已有 ...

  6. ASP.NET MVC5 + EF6 入门教程 (6) View中的Razor使用

    文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-ef-6-get-started-model.html 上一节:ASP.NET MVC ...

  7. 构建ASP.NET MVC5+EF6+EasyUI 1.4.3+Unity4.x注入的后台管理系统

    开篇:从50开始系统已经由MVC4+EF5+UNITY2.X+Quartz 2.0+easyui 1.3.4无缝接入 MVC5+EF6+Unity4.x+Quartz 2.3 +easyui 1.4. ...

  8. [Asp.net MVC]Asp.net MVC5系列——Razor语法

    Razor视图引擎是Asp.net MVC3中新扩展的内容,并且也是它的默认视图引擎.还有另外一种Web Forms视图引擎.通过前面的文章可知在Asp.net mvc5中创建视图,默认使用的是Raz ...

  9. 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](五)

    前言 Hi,大家好,我是Rector 时间飞逝,一个星期又过去了,今天还是星期五,Rector在图享网继续跟大家分享系列文本:一步一步创建ASP.NET MVC5程序[Repository+Autof ...

随机推荐

  1. Python基础教程2上的一处打印缺陷导致的代码不完整#1

    #1对代码的完善的 出现打印代码处缺陷截图: 图片上可以看到,定义的request根本没有定义它就有了.这个是未定义的,会报错的,这本书印刷问题,这个就是个坑,我也是才发现.花了点时间脱坑. 现在发完 ...

  2. Python学习day1 初识python&环境安装

    day1 环境安装-计算机基础 环境安装参见 https://blog.csdn.net/ling_mochen/article/details/79314118 1.markdown基本语法 htt ...

  3. spring activemq 整合

    创建maven项目 项目目录结构为 首先配置相关maven依赖 <!-- 版本管理 --> <properties> <springframework>4.1.8. ...

  4. vue--传值

    传值:(如果传的是引用类型,当值发生改变时所有绑定他的全都发生改变,如果传的时值类型,就只有他自己发生改变) 父传子: 父页面:父组件定义一个属性 users:[ {name:'张三',positio ...

  5. codeforces Hello 2019(未写完)

    A. Gennady and a Card Game a题惯例签到题 题意:给你一张牌,再给你5张牌,判断能不能出一次牌... 所以只要检查第二行中的某个卡是否与第一行中的卡具有共同字符 有就输出YE ...

  6. 在gitlab新建空项目,将本地的git仓库的内容上传

    gitlab新建了这个项目. 按照官网的步骤上传代码 一:将本地代码上传到本地仓库 1.进入项目文件夹 git init 2.项目代码添加到本地git git add . 3.提交到stage区域 g ...

  7. HomeFragment 嵌套关系

    1.HomeFragment 在mainActivty 中调用: 2.HomeFragment 中: private ArrayList<Fragment> mFragments = ne ...

  8. Vue(基础四)_总结五种父子组件之间的通信方式

    一.前言 这篇文章主要总结了几种通信方式: 1.方式一:使用props: [ ]和$emit()  (适用于单层通信) 2.方式二:$attrs和$listeners(适用于多层) 3.方式三:中央处 ...

  9. Python之包

    包是一种通过使用'.模块名'来组织python模块名称空间的方式.创建包是为了用文件夹将文件/模块组织起来,创建包的目的不是为了运行,而是为了被导入使用.包的本质就是一个文件,其功能是将文件组织起来, ...

  10. go 方法

    go 方法 Golang中的任何自定义类型,都可以有方法,而不仅仅是struct. 定义:func (recevier type) methodName(参数列表)(返回值列表){} 方法的访问控制, ...