如何从ASPNET Core中的资源文件中获取特定密钥的值? [英] How to get value of specific key from resource file in ASPNET Core?
本文介绍了如何从ASPNET Core中的资源文件中获取特定密钥的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取.net核心API中资源(.resx)文件中密钥的值.我遵循标记的答案并在我的代码中实现.但是,当我按键获取值时,只会出现键名称.
I wanna get value of a key in resource (.resx) file in .net core API. I followed the marked answer and implemented in my code. But When I am fetching value by key then only Key name is coming.
下面是我关注的链接:
请为此帮助我.
谢谢
推荐答案
这是一个可行的示例,您可以参考:
Here is a working example , you could refer to :
Startup.cs
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
var connection = @"Server=(localdb)\mssqllocaldb;Database=WebAPIDbContext;Trusted_Connection=True;ConnectRetryCount=0";
services.AddDbContext<RestaurantContext>(options => options.UseSqlServer(connection));
services.AddLocalization(o => o.ResourcesPath = "Resources");
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//Request Localization
//var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
//app.UseRequestLocalization(options.Value);
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("zh-cn"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
app.UseHttpsRedirection();
app.UseMvc();
}
控制器
private readonly IStringLocalizer<SharedResource> _sharedLocalizer;
public ValuesController(IStringLocalizer<SharedResource> sharedLocalizer)
{
_sharedLocalizer = sharedLocalizer;
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
var value = _sharedLocalizer["Title"];
return "value";
}
资源文件路径
注意:SharedResource.cs的命名空间应为应用程序的根
Note : the namespace of SharedResource.cs should be the root of application
namespace RestaurantReviewApi
{
public class SharedResource
{
}
}
请求网址:https://localhost:44318/api/values/3?culture=zh-cn
结果的屏幕截图:
参考资料: https://docs .microsoft.com/en-us/aspnet/core/fundamentals/localization?view = aspnetcore-2.2
这篇关于如何从ASPNET Core中的资源文件中获取特定密钥的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文