我正在使用库 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);
}
请帮忙。