如何修复验证错误Net Core 2.2 Web API中的响应

问题描述 投票:0回答:1

我正在处理asp.net core-2.2错误,但我仍然从Response获取错误消息详细信息

我有一个登录和注册方法,其中包含所需的用户名,密码和所需的密码长度,用于注册8到4个字符之间的问题是我收到了预期或处理登录方法的错误消息,当我注册时出现验证错误空用户名和密码。

我在ConfigureApiBehaviorOptions中添加了这段代码:

options.SuppressModelStateInvalidFilter = true;

而我也尝试了这个选项:

options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;

但它不起作用。

这是我的注册DTO:

using System.ComponentModel.DataAnnotations;

namespace DatingApp.Api.Dtos
{
    public class UserForRegisterDto
    {
        [Required]
        public string Username { get; set; }
        [Required]
        [StringLength(8, MinimumLength= 4, ErrorMessage= "password between 4 and 8 charracters")]
        public string Password { get; set; }
    }
}

我期待这个错误消息:

“密码在4到8个字符之间”

但是在我改变ConfigureApiBehaviorOptions之前我得到了这个:

“title”:“发生一个或多个验证错误。”,“status”:400,“traceId”:“0HLJIO56EGJEV:00000001”

如果我使用ConfigureApiBehaviorOptions,还有一个包含错误详细信息的完整表格。

asp.net-core-2.2
1个回答
0
投票
  public class UserForRegisterDto
    {
        [Required(ErrorMessage = "username is required")]
        public string Username { get; set; }
        [Required(ErrorMessage = "password is required")]
        [StringLength(8, MinimumLength= 4, ErrorMessage= "password between 4 and 8 charracters")]
        public string Password { get; set; }
    }

我只是为必填字段添加错误消息。

© www.soinside.com 2019 - 2024. All rights reserved.