[英]In .Net Core how to validate the password before entering in Controller Action?
這是我的 DTO 注冊請求:
public class RegistrationRequestDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Compare("Password")]
public string PasswordConfirmation { get; set; }
}
當我看到“[DataType(DataType.Password)]”時,我希望框架檢查密碼是否遵守來自身份框架的規則。 例如,在啟動時我有:
[...]
services
.AddIdentity<User, Role>(options =>
{
[...]
options.Password.RequireUppercase = true;
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Password.RequireLowercase = true;
})
[...]
所以我嘗試使用“test”作為密碼我應該有一個錯誤 400 調用 API 來注冊我的新用戶。 但是modelState.isValid總是等於 true。
如何查看密碼?
您只需要使用以下內容裝飾您的視圖模型的屬性:
[Remote(action: "ValidatePassword", controller: "MyValidationController", ErrorMessage = "Remote validation is working")]
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
然后在 controller(在本例中名為“MyValidationController”)中創建一個操作(在本例中名為“ValidatePassword”)並在其中添加您的邏輯:
[AcceptVerbs("Get", "Post")]
public async Task<IActionResult> ValidatePassword(string password)
{
bool isvalid = true;
//
validationLogic
//
if (isvalid)
return Json(data: true);
else
return Json(data: false);
}
參考: 遠程屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.