c# - 登录后覆盖.Net Core "CultureInfo"

标签 c# asp.net-core .net-core cultureinfo asp.net-core-localization

我的应用程序适用于新文化!到目前为止一切顺利!

但是......我想在用户登录后覆盖实际的“CultureInfo”。我必须这样做,因为我需要重置“CultureInfo.DateTimeFormat”与另一个保存在我的数据库中。每个用户都有不同的“DateTimeFormat”,因此我必须在登录后执行此操作!例如在我的 Controller “AccountController”上

启动 - 配置:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseStaticFiles();
        app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = Configuration.GetValue<string>("Authentication:Name"),
            LoginPath = new PathString("/Account/Login/"),
            AccessDeniedPath = new PathString("/Account/Forbidden/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true
        });

        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                "default",
                "{controller=Account}/{action=Login}/{id?}");
        });
    }

启动 - 配置服务:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddLocalization(opt => { opt.ResourcesPath = "Resources"; });

        // Add localization services.
        services.Configure<RequestLocalizationOptions>(
            opts =>
            {
                var cultureList = new List<string>();
                Configuration.GetSection("Culture:Languages").Bind(cultureList);
                var supportedCultures = cultureList.Select(lang => new CultureInfo(lang)).ToList();

                opts.DefaultRequestCulture = new RequestCulture(Configuration.GetValue<string>("Culture:Default"));
                // Formatting numbers, dates, etc.
                opts.SupportedCultures = supportedCultures;
                // UI strings that we have localized.
                opts.SupportedUICultures = supportedCultures;
            });

        // Add framework services.
        services.AddMvc()
                .AddDataAnnotationsLocalization(options =>
                {
                    options.DataAnnotationLocalizerProvider = (type, factory) =>
                        factory.Create(typeof(SharedResources));
                })
                .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; });
    }

账户 Controller :

[HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginDto model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        if (ModelState.IsValid)
        {
            // Validation credentials
            var resultDto = await Repository.Get(model);

            if (resultDto.Errors != null)
            {
                ViewBag.Error = _localizer["Token.Invalid"];
                return View();
            }

            // Reset the CultureInfo
            ...

            return RedirectToAction("Admin", "Dashboard");
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

最佳答案

这是一个关于如何从声明中读取它的示例。只需确保首先添加您的 CustomRequestCultureProvider .Insert(0, ...) 以便在其他提供程序之前调用它。

在此示例中,声明名为 culture

// Add localization services.
services.Configure<RequestLocalizationOptions>(
    opts =>
    {
        var cultureList = new List<string>();
        Configuration.GetSection("Culture:Languages").Bind(cultureList);
        var supportedCultures = cultureList.Select(lang => new CultureInfo(lang)).ToList();

        opts.DefaultRequestCulture = new RequestCulture(Configuration.GetValue<string>("Culture:Default"));
        // Formatting numbers, dates, etc.
        opts.SupportedCultures = supportedCultures;
        // UI strings that we have localized.
        opts.SupportedUICultures = supportedCultures;

        // We add the CustomRequestCultureProvider first, so it's evaluated
        // Before the other 3 (Cookie, Header, Query) 
        localizationOptions.RequestCultureProviders.Insert(0,
            new CustomRequestCultureProvider(httpContext =>
            {
                // When user is not logged in, return null and another
                // CultureProvider may try it's luck
                if (httpContext.User == null)
                    return null;

                // When no claim is set, also return it
                var culture = httpContext.User.FindFirst("culture");
                if (culture?.Value == null)
                    return null;

                // Here we set the language from the claim, since the result is not null
                // other providers won't be evaluated anymore and this language will be chosen
                return Task.FromResult(new ProviderCultureResult(culture.Value));
            })
        );
    });

关于c# - 登录后覆盖.Net Core "CultureInfo",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44698466/

相关文章:

c# - 在 Unity 上使用 .NET 自己的 httpClient 类

c# - 如何将通用存储库(或业务逻辑层)注入(inject) ViewModel

security - 如何创建 API key 和安全 key ?

file - .NET Core 中对文件安全性的支持

entity-framework - EF Core 工具版本更新 2.1.1

c# - 如何禁用 Windows Media Player 中的右键单击

c# - 如何更改c#中窗口窗体的原点即左上角和openGL C即中心?

c# - 中等信任度的 ASP.NET MVC

javascript - 在另一个 ViewComponent 中调用一个 ViewComponent

asp.net-core - Automapper 和 EF 导航属性