从Netcore 2.2 Web API的响应中获取ErrorMessage

时间:2019-01-05 04:06:47

标签: c# asp.net-core asp.net-core-2.2

我用空的用户名和密码调用Register方法。所以我收到了这个结果:

{
    "errors": {
        "Password": [
            "The Password field is required.",
            "Password length is between 4 and 8."
        ],
        "Username": [
            "The Username field is required."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "0HLJIO56EGJEV:00000001"
}

我的Dto:

public class UserForRegisterDto
{
    [Required]
    public string Username { get; set; }
    [Required]
    [StringLength(8, MinimumLength = 4, ErrorMessage = "Password length is between 4 and 8.")]
    public string Password { get; set; }
}

我只想从响应中获取错误属性,该怎么办?

2 个答案:

答案 0 :(得分:3)

这是ASP.NET Core 2.2中的new feature

  

返回客户端错误状态代码(4xx)的IActionResult现在返回ProblemDetails正文。

docs描述了在AddMvc内部调用ConfigureServices时可以禁用此功能,例如:

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;
    });

这将导致2.2之前的行为,该行为只会序列化错误。

答案 1 :(得分:0)

当我经历一个非常接近的场景时,我将在此处添加一个答案,以防其他人遇到相同或相似的问题:

就我而言,问题涉及一个以.NET Core 3.1作为目标框架的项目。我的项目有一个NuGet程序包dll作为其依赖项之一,并且此类程序包具有多个模型。我们的控制器端点将这些模型作为参数。但是,发送到这些端点中的任何一个(以那些模型中的任何一个为主体)的请求引起了对非空引用类型属性的验证错误。

解决该问题的解决方法与Kirk建议的类似。我已经从Startup的ConfigureServices方法向AddControllers方法添加了以下选项:

services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

请注意,通过使用此替代方法,有必要为应用程序周围的可为空的引用类型属性手动添加[Required]属性。

我还在他们的存储库上发布了一个问题:https://github.com/dotnet/aspnetcore/issues/27448

相关问题