我正在基于内置的RegistrationService实现我自己的用户注册服务,所以我复制了大部分内容,包括下面的前几行......
if (EndpointHost.RequestFilters == null
|| !EndpointHost.RequestFilters.Contains(ValidationFilters.RequestFilter)) //Already gets run
RegistrationValidator.ValidateAndThrow(request, ApplyTo.Post);
// Above line does not get hit as there is the ValidationFilters.RequestFilter
//...but then the code should have previously run validation and failed?
//...Adding the following line causes the validation to run and fail when expected
//...but I should not required it as that is the point of the global ValidationFilters.RequestFilter??
RegistrationValidator.ValidateAndThrow(request, ApplyTo.Post);
根据我的理解,ValidationFilters.RequestFilter应该在之前被命中,并且我的验证异常被抛出。
N.B:我已将此行放在apphost配置的最后。
Plugins.Add(new ValidationFeature());
我正在成功注册我的验证器,其中包含:
container.Register<AbstractValidator<UserRegistration>>(new UserRegistrationValidator());
...我现在已经将它缩小到ValidatorCache.cs中的以下ServiceStack源代码行
public class ValidatorCache<T>
{
public static IValidator GetValidator(IHttpRequest httpReq)
{
return httpReq.TryResolve<IValidator<T>>();
}
}
...... TryResolve没有找到验证器。
答案 0 :(得分:2)
我发现验证器没有从IOC容器中解析...而不是深入研究这个我后退了一步,而是找出了为什么自动注册方法以前对我不起作用。
原因是我最初有这个......
public interface IUserRegistrationValidator : IValidator<UserRegistration>
{
}
public class UserRegistrationValidator : AbstractValidator<UserRegistration>, IUserRegistrationValidator
{ //..etc
由于显而易见的原因,ServiceStack代码在线显示如下所示(建议友好例外):
public static void RegisterValidator(this Container container, Type validator, ReuseScope scope=ReuseScope.None)
{
var baseType = validator.BaseType;
while (!baseType.IsGenericType) // WOULD FAIL ON THIS LINE HERE
{
baseType = baseType.BaseType;
}
var dtoType = baseType.GetGenericArguments()[0];
var validatorType = typeof(IValidator<>).MakeGenericType(dtoType);
container.RegisterAutoWiredType(validator, validatorType, scope);
}
在摆脱了我正在玩的无意义接口后,我可以使用注册验证器的自动方法......例如:
container.RegisterValidators(typeof(UserRegistrationValidator).Assembly);
这解决了我的问题,我不是100%确定如何从https://github.com/ServiceStack/ServiceStack/wiki/Validation手动注册UserValidator并让它工作,因为我仍然有点认为以下内容无法正常工作。
container.Register<AbstractValidator<User>>(new UserValidator());
......我当然可能错了!
答案 1 :(得分:1)
您是否考虑在AppHost.cs
?
// This method scans the assembly for validators
container.RegisterValidators(Assemblies);