【问题标题】:FluentValidation ModelState.IsValid always trueFluentValidation ModelState.IsValid 始终为真
【发布时间】:2013-06-28 15:01:56
【问题描述】:

好的,我的问题是来自 fluentValidation 的模型验证器在我的项目中不起作用,无论验证状态如何,ModelState.IsValid 始终为真,我提前使用了 asp.net mvc 4、.net 4.5,谢谢。

全球.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");
    }

【问题讨论】:

  • 你为什么用正确的答案编辑你的问题?

标签: c# asp.net-mvc fluentvalidation


【解决方案1】:

您的Validator 属性似乎有错误的类型。你有:

[Validator(typeof(LoginViewModel))]
public class LoginViewModel

类型参数应该是您的验证器类 - LoginViewModelValidator。所以它会是这样的:

[Validator(typeof(LoginViewModelValidator))]
public class LoginViewModel

【讨论】:

  • 没问题。我去过那儿。 :-) 请不要忘记接受答案。
【解决方案2】:

除了接受的答案: 如果用户使用 Aspnet Core 框架需要在 Statrup.cs 中注册为服务(在 'ConfigureServices' 方法下)

services.AddTransient<IValidator<LoginViewModel>, LoginViewModelValidator>();

[Validator(typeof(LoginViewModelValidator))] 过滤器可能无法按预期工作。

【讨论】:

    【解决方案3】:

    另外,不要忘记注册您的验证器。

    services.AddTransient<IValidator<LoginViewModel>, LoginViewModelValidator>(); 
    

    .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多