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

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. hdu 2594 Simpsons’ Hidden Talents(扩展kmp)

    Problem Description Homer: Marge, I just figured out a way to discover some of the talents we weren’ ...

  2. 牛客练习赛28 E迎风舞 (三分查找)

    链接:https://www.nowcoder.com/acm/contest/200/E来源:牛客网 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 262144K,其他语言5242 ...

  3. pre标签内文本自动换行

    pre标签内文本自动换行 给pre标签添加一个css样式 pre { white-space: pre-wrap; /* css-3 */ white-space: -moz-pre-wrap; /* ...

  4. sha256加密

    sha256: 1.使用npm安装 :npm install js-sha256 2.然后在组件中methods定义方法,在调用 // sha256加密密码 setSha(){ let sha256 ...

  5. 由AC自动机引发的灵感

    一,WA自动机 #include <cstdio> using namespace std; int main() { printf("☺"); ; } 二,TLE自动 ...

  6. vue2.0项目实战(5)vuex快速入门

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式.它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化.Vuex 也集成到 Vue 的官方调试工具  ...

  7. (转)Java动态追踪技术探究

    背景:美团的技术沙龙分享的文章都还是很不错的,通俗易懂,开阔视野,后面又机会要好好实践一番. Java动态追踪技术探究 楔子 jsp的修改 重新加载不需要重启servlet.如何在不重启jvm的情况下 ...

  8. margin纵向重叠

    速记: 如p的纵向 margin 是 16px,那么两个之间纵向的距离是多少?-- 按常理来说应该是 16 + 16 = 32px,但是答案仍然是 16px. 因为纵向的 margin 是会重叠的,如 ...

  9. 第十五节、韦伯局部描述符(WLD,附源码)

    纹理作为一种重要的视觉线索,是图像中普遍存在而又难以描述的特征,图像的纹理特征一般是指图像上地物重复排列造成的灰度值有规则的分布.纹理特征的关键在于纹理特征的提取方法.目前,用于纹理特征提取的方法有很 ...

  10. python config.ini的应用

    config.ini文件的结构是以下这样的:结构是"[ ]"之下是一个section,一部分一部分的结构.以下有三个section,分别为section0,section1,sec ...