我有一个使用资源本地化的ASP.NET Core MVC应用程序。它目前只支持一种文化(fa-IR),我希望根据这种文化处理所有本地化。在ASP.NET Core 1.1中我没有任何问题,但在从ASP.NET Core 1.1迁移到2.1后,我看到每个HTTP请求的此警告:
AcceptLanguageHeaderRequestCultureProvider返回以下不受支持的文化'en-US,en,fa'。
这是我的初创公司:
public class Startup
{
protected CultureInfo DefaultCultureInfo { get; private set; } = new CultureInfo("fa-IR");
public void ConfigureServices(IServiceCollection services)
{
CultureInfo.DefaultThreadCurrentCulture = DefaultCultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = DefaultCultureInfo;
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });
services.AddMemoryCache();
services.AddSession();
services.AddMvc()
.AddDataAnnotationsLocalization()
.AddViewLocalization()
.AddControllersAsServices()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[] { new CultureInfo("fa-IR"), new CultureInfo("en-US") };
options.DefaultRequestCulture = new RequestCulture("fa-IR", "fa-IR");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>
{
return new ProviderCultureResult("fa-IR");
}));
});
}
public void Configure(IApplicationBuilder app)
{
var supportedCultures = new[] { DefaultCultureInfo };
app.UseRequestLocalization(new RequestLocalizationOptions()
{
DefaultRequestCulture = new RequestCulture(DefaultCultureInfo),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures,
FallBackToParentCultures = true,
FallBackToParentUICultures = true,
});
app.UseSession();
app.UseMvc();
app.UseCookiePolicy();
}
}
事实上它只是一个警告,我的应用程序工作正常,但我的日志文件填充此警告,所以我正在寻找一种方法让MVC知道我想要的。
[编辑]:我添加了CustomRequestCultureProvider但没有效果,在该行中设置断点后意识到该行没有被击中。
[Edit2]:正如user2429841建议的那样,我向supportedCultures添加了“fa”警告消失但我的资源文件(名为x.fa-IR.resx)不再被拾取。有没有办法对MVC说,如果你得到一些文化把它当作另一种文化?
作为documented,您可以通过指定每个提供程序的最小日志级别来过滤日志记录。
在您的appsettings.json Logging
配置中添加Microsoft.AspNetCore.Localization并将值设置为Error。在这种情况下,消息将不再出现在日志中。
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information",
"Microsoft.AspNetCore.Localization": "Error" // <-- Disables the warnings
}
},
您的Web浏览器会在Accept-Language-HTTP-Header中发送'en-US,en,fa',而asp.net核心只是告诉您,您不支持任何这种文化。
Kakos649的答案没有意义,因为如果您通过选项服务解析RequestLocalizationtions实例,它将导致相同的结果。
编辑:如果您支持这些语言,警告消失。
services.AddOptions();
将此行添加到Configure方法
app.UseRequestLocalization(
app.ApplicationServices.GetService<IOptions<RequestLocalizationtions>>().Value);
本地化中间件默认使用3个提供程序来确定请求的文化。
按顺序评估它们:
如果您没有设置cookie来获取文化,那么本地化中间件将默认为“Accept-Language header”。
例如:Accept-Language标题“en-US,en,fa”将首先请求美国英语,然后是任何其他英语语言环境,最后是fa-IR。因此,查找en locale的警告是有意义的。
你可以设置一个cookie,你的警告就会消失。
更多细节以及如何设置文化cookie https://joonasw.net/view/aspnet-core-localization-deep-dive