2016-05-17 57 views
4

我有一个验证器,我试图使用一些会话变量作为验证逻辑的一部分,但base.Request总是回来为NULL。我已按照指示将它添加到lambda函数中,并且验证文档似乎已过时,因为Fluent validation for request dtos一节中的提示使用IRequiresHttpRequest,但AbstractValidator类已实现IRequiresRequestServiceStack验证器 - 请求没有注入

这是我的代码:

public class UpdateContact : IReturn<UpdateContactResponse> 
{ 
    public Guid Id { get; set; } 

    public string Reference { get; set; } 

    public string Notes { get; set; } 

    public List<Accounts> Accounts { get; set; } 
} 

public class UpdateContactResponse : ResponseBase 
{ 
    public Guid ContactId { get; set; } 
} 

public class UpdateContactValidator : AbstractValidator<UpdateContact> 
{ 
    public UpdateContactValidator(IValidator<AccountDetail> accountDetailValidator) 
    { 
     RuleSet(ApplyTo.Post | ApplyTo.Put,() => { 
      var session = base.Request.GetSession() as CustomAuthSession; 
      RuleFor(c => c.Reference).Must(x => !string.IsNullOrEmpty(x) && session.Region.GetCountry() == RegionCodes.AU); 
     }); 

     RuleFor(R => R.Accounts).SetCollectionValidator(accountDetailValidator); 
    } 
} 

有我丢失的东西?

回答

4

只能从RuleFor() lambda中完成对注入依赖项的访问,在构造函数初始化时执行RuleSet()中的代理以设置该RuleSet的规则。

所以,你需要RuleFor()拉姆达内base.Request您的访问更改为:

RuleSet(ApplyTo.Post | ApplyTo.Put,() => { 
    RuleFor(c => c.Reference) 
    .Must(x => !string.IsNullOrEmpty(x) && 
    (Request.GetSession() as CustomAuthSession).Region.GetCountry() == RegionCodes.AU); 
}); 
+0

所以更的“执行顺序”知识是特定于SS – Jeff

+1

@Jeff都能跟得上不能做请求流水线,'RuleSet()'lambda在注入依赖关系之前在构造函数中执行,'RuleFor()'lambda在执行验证时执行,这可以访问正确注入的Validators。 – mythz

+1

感谢您为单一级别验证工作,但现在当我添加一个嵌套的验证器'RuleFor(R => R.Accounts).SetCollectionValidator(accountDetailValidator);'accountDetailValidator似乎不解决Request对象。我也更新了这个问题。 – vonec