2014-09-19 32 views
3

我有一個Web API,並在Global.asax中我設置的區域性如下:文化的Web API不使用FluentValidation

protected void Application_PostAuthenticateRequest() 
{ 
    var culture = CultureInfo.CreateSpecificCulture("nl-BE"); 
    Thread.CurrentThread.CurrentCulture = culture; 
    Thread.CurrentThread.CurrentUICulture = culture; 
} 

我已經添加了良好驗證的.NET的NuGet,並因此在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上正確設置區域性。

任何人有一個想法我做錯了什麼?

+1

IIRC在FluentValidation一些消息被翻譯,有些則不是。 – Stijn 2014-09-19 19:35:00

回答

1

感謝Stijn的提示,我開始關注如何使用我自己的資源進行Fluent驗證,這就是我的做法。

在Global.asax中,文化被設置和流利的驗證資源提供者類型設置取決於文化:

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鍵都被定義了,比如包含諸如Between_error等等。另外,像WeightValue這樣的各種屬性在這裏被定義。

最後,在驗證,WithLocalizedName用於本地化的屬性名稱:

RuleFor(command => command.WeightValue).InclusiveBetween(20, 200).WithLocalizedName(() => Prim.Mgp.Infrastructure.Resources.nl_BE.WeightValue);