好的,我的问题是来自 fluentValidation 的模型验证器在我的项目中不起作用,并且无论验证状态如何,ModelState.IsValid 始终为真,我提前使用了 asp.net mvc 4、.net 4.5、thx。
全球.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"); }