2

私のアプリケーションは新しい文化でうまくいっています!ここまでは順調ですね!ログイン後の.Net Core "CultureInfo"

しかし...私はユーザーがログインした後、実際の「のCultureInfo」を上書きしたい。私はこれをしなければならない、私は私のDBに保存された他のものと「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

簡単な解決策の1つは、ユーザーカルチャをスレッドに設定することです。これは実際に最も洗練されたソリューションではありませんが、非常に弾力性があり、簡単にコーディングすることができます。 '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)); 
      }) 
     ); 
    }); 
関連する問題