c# - 使用 ASP.NET MVC 实现全局化

标签 c# asp.net-mvc globalization resx spark-view-engine

我正在使用 spark viewengine、asp.net mvc 和 .resx 文件。

我想通过我的自定义 SessionModel(Session)设置一种语言,它是通过 CaSTLe.Windsor 注册的,并且具有 Culture 的字符串属性,可以由用户设置...

我需要在每个 View 上保留当前语言,而不必不断设置当前 UICulture。

不必在每个 Controller 操作中每次都这样做:

    public SessionModel SessionModel { get; set; }

    public ActionResult Index()
    {
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(SessionModel.Culture);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }

这样做的问题是,如果我转到另一个页面,当前文化将翻转回默认语言。

在我简单调用的 spark View 上,获取当前文化:

${SR.Home}

SR.resx 包含 Home 的公共(public)条目。

有没有人知道如何做到这一点,我应该用 ActionFilter 来做到这一点吗?

最佳答案

Action 过滤器似乎是个好主意:

public class SetCultureActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        CultureInfo culture = FetchCultureFromContext(filterContext);
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;
        base.OnActionExecuting(filterContext);
    }

    private CultureInfo FetchCultureFromContext(ActionExecutingContext filterContext)
    {
        throw new NotImplementedException();
    }
}

然后用这个属性装饰你的基础 Controller 。

关于c# - 使用 ASP.NET MVC 实现全局化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4116591/

相关文章:

c# - ASP.Net Entity Framework 和外键

c# - Entity Framework ICollection 导航属性仅在测试时为 null

ibm-cloud - IBM Bluemix Globalization Pipeline 中的 {placeholder} 处理

asp.net - 多语言站点随机更改语言

c# - 我怎样才能制作一个可以加密其他程序然后解密它们的程序?

c# - MonoDevelop 3.1.1 找不到 System.Xml.Linq

c# - 将 LINQ-to-SQL 对象转换为模型对象的好方法是什么?

c# - 只读文本框的服务器验证 - 防止输入值

c# - 将 .NET 区域设置转换为 jQuery 区域设置 - 当本地资源中不存在国家变体(例如 "-US"或 "-MX")时

c# - 可选参数后跟 Params