问题
I call Register method with empty username and password. So I received this result:
{
"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"
}
My 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; }
}
I only want to get errors attribute from response, What should I do?
回答1:
This is a new feature in ASP.NET Core 2.2:
An
IActionResult
returning a client error status code (4xx) now returns aProblemDetails
body.
The docs describe that this can be disabled when calling AddMvc
inside of ConfigureServices
, like this:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressUseValidationProblemDetailsForInvalidModelStateResponses = true;
});
This will result in the pre-2.2 behavior, which will serialise only the errors.
来源:https://stackoverflow.com/questions/54048880/get-errormessage-from-response-in-netcore-2-2-web-api