话不多说直接上代码:
1.新建一个资源文件:
2.新建一个过滤器
public class LocalizationAttribute : ActionFilterAttribute
{
///
/// 在Action执行时获取路由的lang值
///
///
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[“Language”];
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(“Language”, Thread.CurrentThread.CurrentUICulture.Name);
_cookie.Expires = DateTime.Now.AddYears(1);
filterContext.HttpContext.Response.SetCookie(_cookie);
base.OnActionExecuting(filterContext);}}
3,在页面使用资源文件 访问里面对应的字段
4.配置路由
/添加一个路由 多语言设置/
routes.MapRoute(
name: “Localization”, // 路由名称
url: “{lang}/{controller}/{action}/{id}”, // 带有参数的 URL
constraints: new { lang = “zh-CN|en-US” }, //限制可输入的语言项
defaults: new { lang=“zh-CN”,controller = “Home”, action = “Index”, id = UrlParameter.Optional }//参数默认值
);
5.运行结果
默认zh-CN
http://localhost:10996/Home/Index
http://localhost:10996/en-US/Home/Index