gpt4 book ai didi

c# - ASP.NET 核心 3.1 : Shared Localization not working for version 3. 1

转载 作者:行者123 更新时间:2023-12-03 20:19:20 25 4
gpt4 key购买 nike

我可能没有在 startup.cs 中进行正确的配置文件。我创建了一个演示应用程序以使其正常工作,但是在尝试了各种操作后它不起作用。演示存储库可在以下链接中获得

https://github.com/gurpreet42/MyAppV3

startup.cs 文件的配置是

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<LocService>();
services.AddLocalization(options => options.ResourcesPath = "Resources");

services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("nl")
};

options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});

services.AddMvc()
.AddViewLocalization()
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
return factory.Create("SharedResource", assemblyName.Name);
};
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
// Localisation
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseSession();

app.UseSession();
app.UseCookiePolicy();
}
LocService中的代码类(class)是
public class LocService
{
private readonly IStringLocalizer _localizer;

public LocService(IStringLocalizerFactory factory)
{
var type = typeof(SharedResource);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
_localizer = factory.Create("SharedResource", assemblyName.Name);
}

public LocalizedString GetLocalizedHtmlString(string key)
{
var value= _localizer[key];
return value;
}
}

现在在我们的 Controller 上,我们可以访问本地化的字符串
localizerService.GetLocalizedHtmlString("my_string")

在“资源”文件夹下,我们有以下文件
SharedResource.cs
SharedResource.en-US.resx
SharedResource.nl.resx

请建议配置错误的地方还是我需要添加一些额外的包?

最佳答案

原来在asp.net core 3.1中,需要放置SharedResource.csResources文件夹(见此 github issue)

如果类SharedResource.csSharedResource.*.resx在同一文件夹中,命名空间将在编译的 dll 中出错 xxx.lang.dll .

所以,删除原来的SharedResource.cs直接在项目下新建一个:

namespace MyAppV3
{
public class SharedResource
{
}
}

并将资源文件读到 Resources文件夹。

关于c# - ASP.NET 核心 3.1 : Shared Localization not working for version 3. 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60019136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com