asp.net mvc 多语言环境配置
新建资源文件夹
- 添加 ASP.NET 文件夹
- 选择 App_GlobalResources
新建资源文件
- language.resx
- language.en.resx
创建了中文、英文两个语言的资源文件,中文是程序的默认语言。
然后是 language.en.resx
,中间的“en”是英语的 Culture Name
。如果你需要法语,那么你只需要再创建language.fr.resx
文件,Visual Studio 会自动生成对应的类。
设置资源文件属性
添加过滤器
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1
{
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[0];
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(1);
filterContext.HttpContext.Response.SetCookie(_cookie);
base.OnActionExecuting(filterContext);
}
}
}
添加过滤器
filters.Add(new LocalizationAttribute());
添加路由
routes.MapRoute(
"Localization", // 路由名称
"{lang}/{controller}/{action}/{id}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional }//参数默认值
);
访问资源
ViewBag.name = language.name;