简体   繁体   English

ASP.NET Core 2.0中的字段验证

[英]Field validation in ASP.NET Core 2.0

I get a JSON string in a body of a POST Request like this: 我在POST请求的主体中得到一个JSON字符串,如下所示:

{
  "payload": {
    "email": "example@test.com",
    "password": "example"
  }
}

My question is, how can I validate the email and password field in ASP.NET Core 2.0 ? 我的问题是,如何验证ASP.NET Core 2.0中电子邮件密码字段?

First, create the model with data annotation validation attributes. 首先,使用数据注释验证属性创建模型。 There are a number of out of the box validation attributes, and you can also create your own. 有许多现成的验证属性,您也可以创建自己的验证属性。

public class SomeRequest
{
    [Required]
    public SomeRequestPayload Payload {get;set;}
}
public class SomeRequestPayload
{
    [RegularExpression("some regex", ErrorMessage = "Invalid Email")]
    [Required]
    public string Email {get;set;}
    [RegularExpression("some regex", ErrorMessage = "Invalid Password")]
    [Required]
    public string Password {get;set;}
}

Then check the ModelState in your controller action. 然后在控制器操作中检查ModelState MVC will validate the model and hold any errors in the ModelState when it binds the request body to the method parameter. 当MVC将请求主体绑定到方法参数时,它将验证模型并在ModelState保留任何错误。

[HttpPost("")]
public async Task<IActionResult> PostPayload([FromBody] SomeRequest someRequest)
{
    //checking if there was even a body sent
    if(someRequest == null)
         return this.BadRequest("empty");
    //checking if the body had any errors
    if(!this.ModelState.IsValid)
         return this.BadRequest(this.ModelState);
    //do insert here
    return this.Created("someLocation", someModel);
}

There are many way to validate those fields. 有很多方法可以验证这些字段。 I prefer to use FluentValidation library with additional package FluentValidation.AspNetCore , which integrates validation into ASP.NET Core pipeline . 我更喜欢将FluentValidation库与其他软件包FluentValidation.AspNetCore一起使用,该软件包将验证集成到ASP.NET Core pipeline

There is a great blog-post about using this approach. 关于使用这种方法,有一篇很棒的博客文章

Put simply, you should do a few steps: 简而言之,您应该执行一些步骤:

dotnet add package FluentValidation.AspNetCore

public class AuthViewModelValidator : AbstractValidator<AuthViewModel>
{
    public AuthViewModelValidator()
    {
        RuleFor(reg => reg.Email).NotEmpty().EmailAddress();
        RuleFor(reg => reg.Password).NotEmpty();
    }
}

Add some code to ConfigureServices 将一些代码添加到ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddFluentValidation(fvc =>
                fvc.RegisterValidatorsFromAssemblyContaining<Startup>());
}

And finally validate a model 最后验证模型

[HttpPost]
public IActionResult FormValidation(AuthViewModel model)
{
    if (this.ModelState.IsValid) {
        ViewBag.SuccessMessage = "Great!";
    }
    return View();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM