问题
I am trying to set up localization in my ASP.Net Core Web API project.
I did some research and understand that there is a localization middleware with predefined request culture providers (which in my case are not acceptable), so I need to write a custom request culture provider, something like
public class CustomCultureProvider : RequestCultureProvider
{
public override async Task<ProviderCultureResult> ChangeCulture(HttpContext httpContext)
{
// Return a culture...
return new ProviderCultureResult("en-US");
}
}
What I don't understand is how I can change the culture from a controller, that is, when an endpoint is called.
回答1:
Here is a working demo for asp.net core 3.x that could switch three languages to display the response:
1.Custom RouteDataRequestCultureProvider
:
public class CustomRouteDataRequestCultureProvider : RequestCultureProvider
{
public int IndexOfCulture;
public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
if (httpContext == null)
throw new ArgumentNullException(nameof(httpContext));
string culture = null;
var twoLetterCultureName = httpContext.Request.Path.Value.Split('/')[IndexOfCulture]?.ToString();
if (twoLetterCultureName == "de" )
culture = twoLetterCultureName;
else if (twoLetterCultureName == "fr")
culture = twoLetterCultureName;
else if(twoLetterCultureName =="en")
culture = twoLetterCultureName;
if (culture == null)
return NullProviderCultureResult;
var providerResultCulture = new ProviderCultureResult(culture);
return Task.FromResult(providerResultCulture);
}
}
2.Startup.cs:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddControllers().AddViewLocalization(
LanguageViewLocationExpanderFormat.Suffix,
opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(options => {
var supportedCultures = new CultureInfo[] {
new CultureInfo("en"),
new CultureInfo("de"),
new CultureInfo("fr")
};
options.DefaultRequestCulture = new RequestCulture("en");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new[]{ new CustomRouteDataRequestCultureProvider{
IndexOfCulture=1,
}};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(options.Value);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllerRoute("LocalizedDefault", "{culture:cultrue}/{controller=Home}/{action=Index}/{id?}");
});
}
Test the project:
1.Create folder Resources/Controllers
.
2.Create resource file and named as [ControllerName].[Language].resx
like below:
3.Edit the content of resource file(i.e. ValuesController.de.resx):
4.Create a Controller:
[Route("{culture?}/api/[controller]")]
public class ValuesController : Controller
{
private readonly IStringLocalizer<ValuesController> _localizer;
public ValuesController(IStringLocalizer<ValuesController> localizer)
{
_localizer = localizer;
}
// GET: api/<controller>
[HttpGet]
public IActionResult Get()
{
return new ObjectResult(_localizer["Hi"]);
}
}
Result:
来源:https://stackoverflow.com/questions/60438050/asp-net-core-set-default-culture-from-controller