一般语言调整在哪里?

时间:2013-08-15 19:18:12

标签: asp.net .net asp.net-mvc internationalization

嗯,标题说明了一切。

我现在在我的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);
    };

当您从共享布局页面上的dopdown中选择一个新语言时设置语言(这适用于btw,分别选择不同的语言触发器,正确地选择上下类)。

    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]属性。 是不是有一个文件我可以放置这个,每次我去另一个页面都会改变我的语言?

1 个答案:

答案 0 :(得分:1)

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

  

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

这不是你的情况吗?