我正在使用ServiceStack(使用新API)并尝试验证DTO。刚刚创建了一些简单的代码来模拟验证,但它显然没有触发,或者至少它没有按预期显示响应中的错误。我的代码如下:
DTO:
[Route("/users/login")]
public class UserLogin
{
public string Email { get; set; }
public string Password { get; set; }
}
验证器本身:
public class UserLoginValidator : AbstractValidator<UserLogin>
{
public UserLoginValidator()
{
RuleSet(ApplyTo.Get, () =>
{
RuleFor(x => x.Email).NotEmpty().WithMessage("Please enter your e-mail.");
RuleFor(x => x.Email).EmailAddress().WithMessage("Invalid e-mail.");
RuleFor(x => x.Password).NotEmpty().WithMessage("Please enter your password.");
});
}
}
在主机中配置验证:
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(UserLoginValidator).Assembly);
服务:
public class LoginService : Service
{
public object Get(UserLogin request)
{
var response = new { SessionId = Guid.NewGuid() };
return response;
}
}
是否需要进行其他配置或调整才能使其正常工作?
谢谢!
答案 0 :(得分:2)
注意:响应DTO必须遵循{Request DTO}响应命名 约定,并且必须与请求DTO在同一名称空间中!
尝试为响应创建一个类
public class UserLoginResponse
{
public UserLogin Result { get; set; }
}
并将其归还
public class LoginService : Service
{
public object Get(UserLogin request)
{
var response = new UserLoginResponse { Result = request };
return response;
}
}