2

我的應用程序在新文化中運行良好!到現在爲止還挺好!登錄後覆蓋.Net Core「CultureInfo」

但是...我想覆蓋的實際「的CultureInfo」在用戶登錄後,我必須這樣做,因爲我需要重置「請將CultureInfo.DateTimeFormat」與保存在我的數據庫另一種。每個用戶都有不同的「DateTimeFormat」,因此我必須在登錄後執行此操作!例如在我的控制器 「的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?}"); 
     }); 
    } 

啓動 - ConfigureServices

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"; }); 
    } 

的AccountController

[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); 
    } 
+0

你不能存儲本地化的要求和使用/加'CustomRequestCultureProvider'到您的供應商名單? – Tseng

+0

我可以在登錄後將用戶文化保存爲索賠...但是...如何在登錄後使用CustomRequestCultureProvider? – JhobanyPena

+0

一個簡單的解決方案是將用戶文化設置爲線程。這不是最優雅的解決方案,但它非常防彈,易於編碼。 'Thread.CurrentCulture' https://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture(v=vs.110).aspx – Svek

回答

0

下面是關於如何從索賠中讀取它的示例。只要確保你的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)); 
      }) 
     ); 
    });