asp.net mvc5 多语言应用

时间:2023-03-09 19:45:34
asp.net mvc5 多语言应用

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

1、创建一个mvc项目:

asp.net mvc5 多语言应用

2、创建App_GlobalResources

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

asp.net mvc5 多语言应用

asp.net mvc5 多语言应用

asp.net mvc5 多语言应用

asp.net mvc5 多语言应用

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

asp.net mvc5 多语言应用

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

asp.net mvc5 多语言应用