gpt4 book ai didi

c# - 从 Net Core 2.2 Web API 中的响应获取错误消息

转载 作者:行者123 更新时间:2023-11-30 21:30:41 26 4
gpt4 key购买 nike

我用空的用户名和密码调用 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; }
}

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

最佳答案

这是一个 new feature在 ASP.NET Core 2.2 中:

An IActionResult returning a client error status code (4xx) now returns a ProblemDetails body.

docs描述在 ConfigureServices 中调用 AddMvc 时可以禁用它,如下所示:

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

这将导致 2.2 之前的行为,即仅序列化错误。

关于c# - 从 Net Core 2.2 Web API 中的响应获取错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54048880/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com