簡體   English   中英

ASP.NET Core 2.0中的字段驗證

[英]Field validation in ASP.NET Core 2.0

我在POST請求的主體中得到一個JSON字符串,如下所示:

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

我的問題是,如何驗證ASP.NET Core 2.0中電子郵件密碼字段?

首先,使用數據注釋驗證屬性創建模型。 有許多現成的驗證屬性,您也可以創建自己的驗證屬性。

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;}
}

然后在控制器操作中檢查ModelState 當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);
}

有很多方法可以驗證這些字段。 我更喜歡將FluentValidation庫與其他軟件包FluentValidation.AspNetCore一起使用,該軟件包將驗證集成到ASP.NET Core pipeline

關於使用這種方法,有一篇很棒的博客文章

簡而言之,您應該執行一些步驟:

dotnet add package FluentValidation.AspNetCore

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

將一些代碼添加到ConfigureServices

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

最后驗證模型

[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