代码之家  ›  专栏  ›  技术社区  ›  ZIADIA Oussama

ASP.NET核心2.1本地化

  •  2
  • ZIADIA Oussama  · 技术社区  · 6 年前

    我刚接触到ASP.NET核心,尝试实现本地化以支持多种语言,我的配置如下

     services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.Configure<RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("fr-FR")
                };
                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;
    
            });
            services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix,opts=> {opts.ResourcesPath="Resources"; })
                .AddDataAnnotationsLocalization(o=> {
                o.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    return factory.Create(typeof(SharedResource));
                };
            });
    

    这是标准配置,工作正常,我在控制器中创建了一个方法

     [Route("api/setlanguage")]
        [HttpPost]
        public IActionResult SetLanguage (string culture)
        {
    
            Response.Cookies.Append(
                CookieRequestCultureProvider.DefaultCookieName,
                CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
                new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });
            throw new Exception(_localizer["Hello",culture]);
    
    
        }
    

    当我像这样和邮递员测试时: http://localhost:31563/api/SetLanguage?culture=en-US 我得到了一个正确的结果,但是当我试图传递请求体内的文化时,它不起作用,有人能帮我吗,非常感谢

    2 回复  |  直到 6 年前
        1
  •  1
  •   ZIADIA Oussama    6 年前

      System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
      System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
    

     public IActionResult SetLanguage([FromBody] string culture)
         {          
    
            System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
    
           _localizer.WithCulture(new CultureInfo(culture));
    
        }
    
        2
  •  0
  •   Edward    6 年前
    Body [FromBody]

        public IActionResult SetLanguage([FromBody]string culture)
    

    enter image description here

    Query String