首页 > 解决方案 > 如何在 ASP.Net Core 中设置全球化文化?

问题描述

我在 asp net core mvc 中遇到了十进制数的问题。通过将其添加到 web.config,我让它在常规的 asp 网络应用程序中工作:

  <system.web>
    ...
    <globalization uiCulture="en" culture="en-US"/>
  </system.web>

但是,由于核心应用程序中没有 web.config,我不太确定该怎么做。核心中最接近的近似值会是什么样子?

标签: asp.netasp.net-mvcasp.net-coreasp.net-web-api

解决方案


在 Asp.Net Core 中,本地化是在 Startup.ConfigureServices 方法中配置的,并且可以在整个应用程序中使用:

services.AddLocalization(options => options.ResourcesPath = "Resources");

services.AddMvc()
  .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
  .AddDataAnnotationsLocalization();

请求的当前文化在本地化中间件中设置。该Startup.Configure方法中启用了本地化中间件。必须在任何可能检查请求文化的中间件之前配置本地化中间件(例如,app.UseMvcWithDefaultRoute())。

var supportedCultures = new[]
{
 new CultureInfo("en-US"),
 new CultureInfo("fr"),
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
   DefaultRequestCulture = new RequestCulture("en-US"),
   // Formatting numbers, dates, etc.
   SupportedCultures = supportedCultures,
   // UI strings that we have localized.
   SupportedUICultures = supportedCultures
 });

 app.UseStaticFiles();
 // To configure external authentication, 
 // see: http://go.microsoft.com/fwlink/?LinkID=532715
app.UseAuthentication();
app.UseMvcWithDefaultRoute();

更详细的可以参考官方文档


推荐阅读