[英]How to envelope web api response conventionally int .netcore api
[英]Get ErrorMessage from Response in Netcore 2.2 Web API
我用空的用户名和密码调用 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; }
}
我只想从响应中获取错误属性,我该怎么办?
这是 ASP.NET Core 2.2 中的一项新功能:
一个
IActionResult
返回客户端错误状态代码(4XX)现在返回一个ProblemDetails
体。
文档描述了在ConfigureServices
内部调用AddMvc
时可以禁用此功能,如下所示:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;
});
这将导致 2.2 之前的行为,它只会序列化错误。
当我经历了一个非常接近的场景时,我会在这里添加一个答案,以防其他人遇到相同或类似的问题:
就我而言,问题涉及一个以 .NET Core 3.1 作为目标框架的项目。 我的项目有一个 NuGet 包 dll 作为它的依赖项之一,这样的包有几个模型。 我们的控制器端点将这些模型作为参数。 但是,发送到这些端点中的任何一个(以这些模型中的任何一个作为主体)的请求都会导致不可为空的引用类型属性的验证错误。
解决此问题的解决方法与 Kirk 建议的方法类似。 我在 Startup 的 ConfigureServices 方法中向 AddControllers 方法添加了以下选项:
services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
请注意,通过使用此解决方法,需要为应用程序周围的可为空引用类型属性手动添加 [Required] 属性。
我还在他们的存储库中打开了一个问题: https : //github.com/dotnet/aspnetcore/issues/27448
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.