model.isvalid mvc servicestack流畅的验证

时间:2013-05-25 16:04:56

标签: asp.net-mvc asp.net-mvc-3 servicestack fluentvalidation

我正在使用库servicestack,我在使用库ServiceStack.FluentValidation.Mvc3时遇到问题,我按照步骤配置了这个库,让asp.net mvc引擎识别Model.IsValid属性,但这总是如此。这是我在我的应用程序中提供的验证设置代码片段。

public class AppHost: AppHostBase
{
    public AppHost() : base("Api Services", typeof(AppHost).Assembly)
    {
    }
    //Provide extra validation for the registration process
    public class CustomRegistrationValidator : RegistrationValidator
    {
        public CustomRegistrationValidator()
        {
            RuleSet(ApplyTo.Post, () =>
            {
                RuleFor(x => x.DisplayName).NotEmpty().WithMessage("Ingresa tu nombre de usuario");
                RuleFor(x => x.LastName).NotEmpty().WithMessage("Ingresa tu apellido");
                RuleFor(x => x.Name).NotEmpty().WithMessage("Ingresa tu nombre");
            });
        }
    }

    public class CustomAuthValidator : AbstractValidator<Auth>
    {
        public CustomAuthValidator()
        {
            RuleFor(x => x.UserName).NotEmpty().WithMessage("Ingresa tu nombre de usuario").WithName("Nombre de Usuario");
            RuleFor(x => x.Password).NotEmpty().WithMessage("Ingresa tu contraseña").WithName("Contraseña");
        } 
    }
    public override void Configure(Container container)
    {
        container.Adapter = new WindsorContainerAdapter();

        Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] {
            new CredentialsAuthProvider(),    
            new BasicAuthProvider()}));


        Plugins.Add(new RegistrationFeature());
        Plugins.Add(new ValidationFeature());

        container.RegisterAs<CustomRegistrationValidator, IValidator<Registration>>();
        container.RegisterAs<CustomAuthValidator, IValidator<Auth>>();

        FluentValidationModelValidatorProvider.Configure();

        container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));
        container.Register(c => c.Resolve<IRedisClientsManager>().GetCacheClient()).ReusedWithin(Funq.ReuseScope.None);

        container.Register<IResourceManager>(new ConfigurationResourceManager());



        ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        ServiceStackController.CatchAllController = reqCtx => container.TryResolve<AccountController>();

    }


    public static void Start()
    {
        new AppHost().Init();
    } 
}

邮件错误是默认错误,不会更改我在显示的代码中设置的标签名称。

以下是控制器Account中代码的摘录,以查看模型是否有效。

[HttpPost]
public ActionResult LogOn(Auth model, string returnUrl)
{
    //This always is true
    if (ModelState.IsValid)
    {
        //TODO: Save database and other action more
    }
    return View(model);
}

请帮忙。

1 个答案:

答案 0 :(得分:2)

这应该有效,但我不知道这是否是最佳解决方案

子类验证并使用ValidatorAttribute

对其进行归属
[Validator(typeof(CustomAuthValidator))]
public class MyAuth : Auth
{
}

更改您的CustomAuthValidator以使用新的MyAuth类型

public class CustomAuthValidator : AbstractValidator<MyAuth>
{
    public CustomAuthValidator()
    {
        RuleFor(x => x.UserName).NotEmpty().WithMessage("Ingresa tu nombre de usuario").WithName("Nombre de Usuario");
        RuleFor(x => x.Password).NotEmpty().WithMessage("Ingresa tu contraseña").WithName("Contraseña");
    }
}

更改您的控制器以采用新的MyAuth类型

[HttpPost]
public ActionResult LogOn(MyAuth model, string returnUrl)
{
    //This should now work as expected
    if (ModelState.IsValid)
    {
        //TODO: Save database and other action more
    }
    return View(model);
}