localization - 使用 ASPNETCore 1.1.1 本地化将当前文化默认设置为浏览器文化

标签 localization core globalization culture

我想知道如何使用 ASPNETCore 1.1.1 将当前文化默认设置为浏览器文化

我按照这个例子 https://andrewlock.net/adding-localisation-to-an-asp-net-core-application/

在我的 startup.cs 中我有这个

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IStringLocalizerFactory, SingleFileResourceManagerStringLocalizerFactory>();
    services.AddLocalization(opts => { opts.ResourcesPath = "Resources"; });

    // Add framework services.
    services.AddMvc()
        .AddViewLocalization(
            LanguageViewLocationExpanderFormat.Suffix,
            opts => { opts.ResourcesPath = "Resources"; })
        .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(
        opts =>
        {
            var supportedCultures = new List<CultureInfo>
            {
                new CultureInfo("en"),
                new CultureInfo("es"),
                new CultureInfo("fr"),
            };

            opts.DefaultRequestCulture = new RequestCulture("fr");
            // Formatting numbers, dates, etc.
            opts.SupportedCultures = supportedCultures;
            // UI strings that we have localized.
            opts.SupportedUICultures = supportedCultures;
        });
}

我有一个语言选择器,我在缓存中添加了 CookieRequestCultureProvider.DefaultCookieName。

        [HttpPost]
        public IActionResult SetLanguage(string culture, string returnUrl)
        {
                Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
            );

            return LocalRedirect(returnUrl);
        }

还有这个资源文件

  • 资源.resx

    资源.en.resx

    资源.es.resx

    Resources.fr.resx

这一切都很好,这里的问题是,每次我调用网站时,我都想获得默认的文化,在本例中是“fr”,但我总是得到最后一个,我在关闭网络之前选择页面。

我怎样才能防止这种情况发生。

最好的问候。

乔丽妮丝

最佳答案

Cookie 不会在用户离开网站时消失,因此由于您将 Cookie 的有效期设置为一年后,用户最后选择的语言将在一年内有效。

与 cookie 不同, session 会在用户离开网站时终止,并且具有相同需求的人已经在 github 上请求了该功能并为其创建了 NuGet 包。

https://github.com/aspnet/Localization/issues/344

https://www.nuget.org/packages/My.AspNetCore.Localization.Session

解决此问题的其他方法是使用较短的到期日期(如果您不需要非常精确)或在检测到用户创建了新 session 时删除 cookie。

关于localization - 使用 ASPNETCore 1.1.1 本地化将当前文化默认设置为浏览器文化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090329/

相关文章:

java - Java 编译器是否针对不同的语言环境进行了翻译?

c# - 在大型 .NET 项目中实现多语言/全局化的最佳方式

java.lang.ArrayIndexOutOfBoundsException : 2 >= 0 异常

c# - 设置全局化 Nuget 包

c# - 在 CultureInfo 中获取当前语言

localization - 安装程序属性选项卡下的 WiX 本地化乱码

asp.net - Request.UserLanguages 数组是如何排序的 - 按优先级还是按字母顺序?

c++ - 核心转储中缺少共享库负载偏移

bash - 使用 bash 编写 Gdb 脚本

powershell - 在 Powershell 中,如何将尾随 'sign' 的字符串转换为数字?