【发布时间】:2022-11-25 12:35:59
【问题描述】:
我正在尝试本地化标准身份错误消息。我看过几个关于这个话题的讨论。我确实设法创建了一个项目并使用了我自己的翻译,但在翻译标准身份错误消息时失败了。我决定创建一个新项目来关注身份错误。构造函数多语言身份错误描述符被调用并返回预期值。当我转到 https://localhost:7067/Identity/Account/Register 并在电子邮件字段标准错误中键入“test”时电子邮件字段不是有效的电子邮件地址。" 显示。当有人可以指导我正确的方向或向我发送一些链接时,我很感激。几个小时后,我决定在这里问问你们。谢谢!
程序.cs
using Localizer.Data;
using Localizer.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddErrorDescriber<MultilanguageIdentityErrorDescriber>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
多语言身份错误描述符.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Localization;
public class MultilanguageIdentityErrorDescriber : IdentityErrorDescriber
{
private readonly IStringLocalizer<SharedResource> _localizer;
public MultilanguageIdentityErrorDescriber(IStringLocalizer<SharedResource> localizer)
{
_localizer = localizer;
// ckecking identityError.Description which returns expected value
var identityError = new IdentityError();
identityError = this.InvalidEmail("email@email.com");
}
public override IdentityError DuplicateEmail(string email)
{
return new IdentityError()
{
Code = nameof(DuplicateEmail),
Description = string.Format(_localizer["Email {0} is already taken."], email)
};
}
public override IdentityError DuplicateUserName(string userName)
{
return new IdentityError()
{
Code = nameof(DuplicateEmail),
Description = string.Format(_localizer["Email {0} is already taken."], userName)
};
}
public override IdentityError InvalidEmail(string email)
{
return new IdentityError
{
Code = nameof(InvalidEmail),
Description = string.Format(_localizer["Email '{email}' is invalid."], email)
};
}
}
【问题讨论】:
标签: c#