Localizer ASP.NET Core 6将不会被保存

huangapple go评论75阅读模式
英文:

Localizer ASP.NET Core 6 will not be saved

问题

I understand your instructions. Here is the translated code:

我在我的本地化程序中遇到了问题。如果我想将网站的语言从英语更改为荷兰语,POST请求确实已发送(通过调试进行了检查)。但是语言始终保持为英语,而不会更改为荷兰语。

我从Microsoft的官方文档中获取了代码,并且我不明白为什么它不起作用。 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization/make-content-localizable?view=aspnetcore-6.0)

我正在使用ASP.NET Core 6

这是我的`program.cs`:
```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite(builder.Configuration.GetConnectionString("Application") ??
                          throw new InvalidOperationException("未找到连接字符串")));

var connectionString = builder.Configuration.GetConnectionString("Users");
builder.Services.AddDbContext<UserDbContext>(options =>
        options.UseSqlite(connectionString ?? throw new InvalidOperationException("未找到连接字符串")));

builder.Services.AddStackExchangeRedisCache(config =>
        config.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddSession();
}

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<UserDbContext>();

builder.Services.Configure<IdentityOptions>(options =>
{
    options.Lockout.AllowedForNewUsers = false;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
    options.Lockout.MaxFailedAccessAttempts = 10;

    options.Password.RequireDigit = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
    options.Password.RequiredLength = 1;
    options.Password.RequiredUniqueChars = 1;
});

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.Configure<RequestLocalizationOptions>(options => {
    var supportedCultures = new[] { "en-US", "nl" };
    options.SetDefaultCulture(supportedCultures[1])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures);
});

builder.Services.AddMvc()
    .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
    .AddDataAnnotationsLocalization();

builder.Services.AddTransient<IEmailSender, EmailSender>();
builder.Services.Configure<AuthMessageSenderOptions>(builder.Configuration.GetSection("AuthMessageSenderOptions"));


var app = builder.Build();

app.UseRequestLocalization(options =>
{
    var questStringCultureProvider = options.RequestCultureProviders[0];    
    options.RequestCultureProviders.RemoveAt(0);
    options.RequestCultureProviders.Insert(1, questStringCultureProvider);
});

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

// 配置HTTP请求管道。
if (!app.Environment.IsDevelopment()) {
    app.UseExceptionHandler("/Home/Error");
    // 默认的HSTS值为30天。您可能希望根据生产情况进行更改,参见 https://aka.ms/aspnetcore-hsts。
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "name",
        pattern: "{name}/{controller=Home}/{action=Index}/{id?}");
    
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "",
        defaults: new { controller="Home", action="Choose" });
});

app.MapRazorPages();
app.UseSession();

app.Run();

我的共享布局文件(_layout.cshtml):

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}
<div title="@Localizer["请求文化提供程序:"] @requestCulture?.Provider?.GetType().Name">
                            <form id="selectLanguage" asp-controller="Home"
                                  asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
                                  method="post" class="form-horizontal" role="form">
                                <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["语言:"]</label>
                                <select name="culture"
                                        onchange="this.form.submit();"
                                        asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
                                </select>
                            </form>
                        </div>

以及HomeController.cs

[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl) 
{
    Response.Cookies.Append(
        CookieRequestCultureProvider.DefaultCookieName,
        CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
    );

    return LocalRedirect(returnUrl);
}
英文:

I have a problem with my Localizer. If I want to change the language of the website from English to Dutch, the POST request does get sent (checked with debugging). Only the language always remains set to English and is not changed to Dutch.

I got the code from Microsoft's own documentation, and I don't understand why it doesn't work. (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/localization/make-content-localizable?view=aspnetcore-6.0)

I am using ASP.NET Core 6.

This is my program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("Application") ??
throw new InvalidOperationException("Connection string not found")));
var connectionString = builder.Configuration.GetConnectionString("Users");
builder.Services.AddDbContext<UserDbContext>(options =>
options.UseSqlite(connectionString ?? throw new InvalidOperationException("Connection string not found")));
builder.Services.AddStackExchangeRedisCache(config =>
config.Configuration = builder.Configuration.GetConnectionString("Redis"));
builder.Services.AddSession();
}
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<UserDbContext>();
builder.Services.Configure<IdentityOptions>(options =>
{
options.Lockout.AllowedForNewUsers = false;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 1;
options.Password.RequiredUniqueChars = 1;
});
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.Configure<RequestLocalizationOptions>(options => {
var supportedCultures = new[] { "en-US", "nl" };
options.SetDefaultCulture(supportedCultures[1])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
});
builder.Services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
builder.Services.AddTransient<IEmailSender, EmailSender>();
builder.Services.Configure<AuthMessageSenderOptions>(builder.Configuration.GetSection("AuthMessageSenderOptions"));
var app = builder.Build();
app.UseRequestLocalization(options =>
{
var questStringCultureProvider = options.RequestCultureProviders[0];    
options.RequestCultureProviders.RemoveAt(0);
options.RequestCultureProviders.Insert(1, questStringCultureProvider);
});
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) {
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "name",
pattern: "{name}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "",
defaults: new { controller="Home", action="Choose" });
});
app.MapRazorPages();
app.UseSession();
app.Run();

My shared layout file (_layout.cshtml):

@{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
.ToList();
var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}
<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
<form id="selectLanguage" asp-controller="Home"
asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
method="post" class="form-horizontal" role="form">
<label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label>
<select name="culture"
onchange="this.form.submit();"
asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
</select>
</form>
</div>

And the HomeController.cs:

[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl) 
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}

答案1

得分: 1

以下是翻译好的部分:

尝试以下操作(在注册服务时不要配置RequestLocalizationOptions部分,而是在中间件中进行配置):

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
    var supportedCultures = new[] { "en-us", "nl" };
    options.SetDefaultCulture(supportedCultures[1])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures);
    var queryStringCultureProvider = options.RequestCultureProviders[0];
    options.RequestCultureProviders.RemoveAt(0);
    options.RequestCultureProviders.Insert(1, queryStringCultureProvider);
    //将服务添加到容器中。
});


var app = builder.Build();


app.UseRequestLocalization();
英文:

Try as below(don't configure RequestLocalizationOptions part when you regist services,part in middleware):

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);
builder.Services.AddLocalization(options =&gt; options.ResourcesPath = &quot;Resources&quot;);
builder.Services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt;
{
var supportedCultures = new[] { &quot;en-us&quot;, &quot;nl&quot; };
options.SetDefaultCulture(supportedCultures[1])
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
var questStringCultureProvider = options.RequestCultureProviders[0];
options.RequestCultureProviders.RemoveAt(0);
options.RequestCultureProviders.Insert(1, questStringCultureProvider);
//Add services to the container.
});
var app = builder.Build();
app.UseRequestLocalization();

It now works well on myside:

Localizer ASP.NET Core 6将不会被保存

答案2

得分: 0

将每个@Localizer[&quot;.......&quot;]更改为@Localizer[&quot;.......&quot;].Value

英文:

change every @Localizer[&quot;.......&quot;] to @Localizer[&quot;.......&quot;].Value

huangapple
  • 本文由 发表于 2023年5月22日 03:30:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定