[英]Culture in Web API not used by FluentValidation
我有一個Web API,在global.asax我設置文化如下:
protected void Application_PostAuthenticateRequest()
{
var culture = CultureInfo.CreateSpecificCulture("nl-BE");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
我已經為.NET nuget添加了Fluent驗證,因此在bin文件夾中我有/nl/FluentValidation.resources.dll。
接下來,我有一個驗證器,如:
public class AddWeightCommandValidator : AbstractValidator<AddWeightCommand>
{
public AddWeightCommandValidator()
{
RuleFor(command => command.PatientId).GreaterThan(0);
RuleFor(command => command.WeightValue).InclusiveBetween(20, 200);
}
}
這是從我的命令調用,如:
new AddWeightCommandValidator().ValidateAndThrow(request);
問題是驗證消息仍然是英文而不是荷蘭語。
如果我調試,就在調用驗證器之前,在CurrentUICulture和CurrentCulture上正確設置了culture。
任何人都知道我做錯了什么?
感謝Stijn的提示,我開始研究如何使用自己的資源進行Fluent驗證,這就是我的工作方式。
在global.asax中,設置了culture,並根據該文化設置Fluent Validation的資源提供程序類型:
protected void Application_PostAuthenticateRequest()
{
// Set culture
var culture = CultureInfo.CreateSpecificCulture("nl-BE");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
// Set Fluent Validation resource based on culture
switch (Thread.CurrentThread.CurrentUICulture.ToString())
{
case "nl-BE":
ValidatorOptions.ResourceProviderType = typeof(Prim.Mgp.Infrastructure.Resources.nl_BE);
break;
}
}
在此之后,Fluent Validation將在相應的資源文件中查找翻譯。
資源文件位於單獨的項目中。 這里定義了所有Fluent Validation鍵,例如inclusivebetween_error等。此外,還定義了WeightValue等各種屬性。
最后,在驗證器中,WithLocalizedName用於本地化屬性名稱:
RuleFor(command => command.WeightValue).InclusiveBetween(20, 200).WithLocalizedName(() => Prim.Mgp.Infrastructure.Resources.nl_BE.WeightValue);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.