ASP.NET MVC5 多语言国际化

话不多说直接上代码:
1.新建一个资源文件:
Key-Value对的形式,key最好和数据库里面的一样,标准化一点。

两个语言的资源文件
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
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

急景流年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值