0

好吧,标题说明了一切。

我现在在 LanguageFilterAttribute 类中执行以下操作:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var request         = filterContext.HttpContext.Request;
        string currentUrl   = request.RawUrl;
        var urlHelper       = new UrlHelper(request.RequestContext);

        string baseurl                      = urlHelper.Content("~");
        string currentLanguageFromUrl       = currentUrl.Split('/')[1];
        string currentLanguageFromCulture   = CultureHelper.CheckCulture();
        var currentLanguageFromCookie       = request.Cookies["_culture"];

        var possibleCultures                = UnitOfWork.CulturesRepository.GetListOfCultureNames();

        if (possibleCultures.All(culture => currentLanguageFromUrl != culture))
        {
            string cultureName;
            string newUrl;

            if (currentLanguageFromCookie != null)
            {
                cultureName = currentLanguageFromCookie.Value;
                CultureHelper.SetCulture(cultureName);
                newUrl = baseurl + cultureName;
                filterContext.Result = new RedirectResult(newUrl);
                return;
            }

            if (currentLanguageFromCulture != null)
            {
                cultureName = currentLanguageFromCulture;
                CultureHelper.SetCulture(cultureName);
                newUrl = baseurl + cultureName;
                filterContext.Result = new RedirectResult(newUrl);
                return;
            }

            cultureName = possibleCultures[0];
            CultureHelper.SetCulture(cultureName);
            newUrl = baseurl + cultureName;
            filterContext.Result = new RedirectResult(newUrl);
            return;
        }

        CultureHelper.SetCulture(currentLanguageFromUrl);

        base.OnActionExecuting(filterContext);
    };

当您从共享布局页面上的下拉菜单中选择新语言时,它会设置语言(顺便说一句,选择不同的语言会分别触发,上面和下面的类正确)。

    public static void SetCulture(string culture)
    {
        var cultureCookie = HttpContext.Current.Request.Cookies["_culture"] ?? new HttpCookie("_culture");
        cultureCookie.Value = culture;
        var request = HttpContext.Current.Request;

        cultureCookie.Domain = request.Url.Host;

        cultureCookie.Expires = DateTime.Now.AddYears(1);
        cultureCookie.Path = "/";
        HttpContext.Current.Response.Cookies.Add(cultureCookie);

        CultureInfo info = CultureInfo.CreateSpecificCulture(culture.ToString());

        Thread.CurrentThread.CurrentCulture = info;
        Thread.CurrentThread.CurrentUICulture = info;

    }

问题在于,您可以猜到,我必须在所有控制器上应用 [LanguageFilter] 属性。是不是有一个文件可以放置它,每次我转到另一个页面时都会改变我的语言?

4

1 回答 1

1

http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx

当一个新的应用程序线程启动时,它的当前文化和当前 UI 文化由当前系统文化定义,而不是由当前线程文化定义。

这不是你的情况吗?

于 2013-08-15T19:25:09.547 回答