好的,我的问题是FluentValidation的ModelValidator在我的项目中不起作用,并且无论验证的状态如何,ModelState.IsValid始终为true。我正在使用asp.net mvc 4、.net 4.5,谢谢提前。
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
FluentValidationModelValidatorProvider.Configure();
}
登录视图模型
using FluentValidation.Attributes;
namespace ViewModel.Cuentas
{
[Validator(typeof(LoginViewModel))]
public class LoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
}
LoginViewModelValidator
using FluentValidation;
using FluentValidation.Results;
namespace ViewModel.Cuentas.Validadores
{
public class LoginViewModelValidator : AbstractValidator<LoginViewModel>
{
public LoginViewModelValidator()
{
RuleFor(x => x.UserName).NotEmpty().WithMessage("El Campo Usuario es Necesario");
RuleFor(x => x.Password).NotEmpty().WithMessage("El Campo Usuario es Necesario");
}
}
}
和我的账户控制器
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View();
}
FormsAuthentication.SetAuthCookie(viewModel.UserName, false);
if (!String.IsNullOrEmpty(returnUrl) && returnUrl != "/")
{
return Redirect(returnUrl);
}
return RedirectToAction("Enviar", "Cartas");
}