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

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. 牛客练习赛31 D神器大师泰兹瑞与威穆

    双链表搞完了 #include<bits/stdc++.h> using namespace std; #define maxn 1000005 int tot,bac[maxn],fa[ ...

  2. HDU/HDOJ 4699 Editor

    对顶栈算法. 此题充分说明了cin的不中以及scanf的优越性. 我TM用cin超时了!!!换成scanf就A了!!! #include <cstdio> #include <cst ...

  3. react-native中的scrollables

    这是一个点击切换的demo 先看效果 然后看实现的代码 import React from 'react'; import { Text, View } from 'react-native'; im ...

  4. 千人基因组(1000 Genomes)提取群体(population)或者样本(sample ID)信息

    进入链接:http://www.internationalgenome.org/data-portal/sample 点击“filter by population”,在弹出的选择框里,选择想要下载的 ...

  5. Nginx上部署HTTPS + HTTP2

    Nginx上部署HTTPS依赖OpenSSL库和包含文件,即须先安装好libssl-dev(或者OpenSSL),且ln -s /usr/lib/x86_64-linux-gnu/libssl.so ...

  6. java的集合

    Collection: 1.list ArrayList.Vector.LinkedList ArrayList是实现了基于动态数组的数据结构,LinkedList基于链表的数据结构. Vector是 ...

  7. 5.1、按键SW1控制LED1亮灭

    从图中可以看出,P1_2引脚可以感知SW1的状态,SW1未按下P1_2=1高电平,按下后P1_2=0接地. 注意:P1_2引脚只是感知SW1,不影响SW1. #include "ioCC25 ...

  8. HTML学习笔记Day3

    一.CSS样式 1.每个css样式都必须由两部分组成:选择符(Selector)+声明(Deleration) 注:声明又包括属性(Properyt)和属性值(value) 2.css属性:属性是指定 ...

  9. Linux(centos7)如何安装Zend Optimizer Zend Guard Loader

    下载地址:http://www.zend.com/en/products/loader/downloads#Linux 1.解压 wget http://downloads.zend.com/guar ...

  10. python自动化开发-[第十七天]-django的ORM与其他

    今日概要: 1.name别名 2.模版的深度查询 3.模版语言之filter 4.自定义过滤器,filter和simpletag的区别 5.orm进阶 扫盲:url的组成 URL:协议+域名+端口+路 ...