ModelState.IsValid为真,但为什么



我有以下登录模型:

public class LoginDto
{
private const string EmailRegex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])";
public LoginDto(string email, string password)
{
this.Email = email;
this.Password = password;
}
[Required(AllowEmptyStrings = false, ErrorMessage = "Email darf nicht leer sein.")]
[RegularExpression(EmailRegex)]
public string Email { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Passwort darf nicht leer sein.")]
public string Password { get; set; }
}

它通过[FromBody]传递到我的控制器方法中。我想通过检查ModelState.IsValid:来检查(电子邮件和密码(是否都为空

[HttpPost("login")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[AllowAnonymous]
public async Task<IActionResult> PostLogin([FromBody] LoginDto loginData)
{
if (!this.ModelState.IsValid) {
return this.BadRequest(new Response(nameof(this.ModelState).ToCamelCase(), this.ModelState)                 {
Status = ResponseStatus.Fail.ToString(),
Code = StatusCodes.Status400BadRequest,
Error = new ErrorObject { Code = "InvalidModelState", Message = "Submitted object doesn't pass it's validation check.", Target = "payload" }
}
...
}

不幸的是,当我传递字符串时。如果电子邮件或密码为空,则ModelState.IsValid仍为true

当其中一个属性为null或为空时,我如何实现ModelState.IsValid就是false

我们使用的是.NET Core 3。

提前感谢

您也可以尝试添加MinLength(1)属性。

还没有测试过,但应该可以工作,我想

我想明白了。我不再需要在.Net Core 3.0中通过检查this.ModelState.IsValid手动验证。当控制器上具有[ApiController]属性时,中间件正在处理它。

[ApiController]属性使模型验证错误自动触发HTTP 400响应。因此,以下代码在操作方法中是不必要的:

if(!ModelState.IsValid({
return BadRequest(ModelState(;

来源:https://learn.microsoft.com/en-us/aspnet/core/web-api/index?view=aspnetcore-2.1#自动-http-400-响应

试着像这个一样将[BindRequired]添加到你的模型中

[Required(AllowEmptyStrings = false, ErrorMessage = "Email darf nicht leer sein.")]
[BindRequired]
[RegularExpression(EmailRegex)]
public string Email { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessage = "Passwort darf nicht leer sein.")]
[BindRequired]
public string Password { get; set; }

你可以在这里阅读更多

最新更新