services.Configure(
options => {
var supportedCultures = new List
{
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
//添加其他语言文化
};
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
//添加CookieRequestCultureProvider
options.RequestCultureProviders.Insert(0, new CookieRequestCultureProvider());
});
此代码指定了项目支持的文化信息并添加了CookieRequestCultureProvider。可以根据项目需要添加其他Provider。 3. 在需要使用多语言时,在Controller或视图中添加以下代码:
var currentCulture = HttpContext.Features.Get().RequestCulture.UICulture;
此代码将获取当前用户的语言环境信息,可以将其用于后续处理。
附上完整示例代码: Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Localization;
using System.Globalization;
using System.Collections.Generic;
using Microsoft.AspNetCore.Localization.Routing;
namespace MvcLocalizationDemo
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.Configure(
options => {
var supportedCultures = new List
{
new CultureInfo("en-US"),
new CultureInfo("fr-FR")
};
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new RouteData