3

I'm developing a Web API in ASP.NET. When I use:

return BadRequest( result.Errors );

The response is just an array of errors. For consistency, I want the errors to be wrapped in the same wrapper as other asp.net errors like below:

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|803e532a-47325349ba863a12.",
"errors": {
    "Password": [
        "The Password field is required."
    ]
}
}

How to achieve this result?

2 Answers2

3

One of the simplest way is to return a ValidationProblemDetails:

ModelState.AddModelError("Password", "Password field is required");
return ValidationProblem(ModelState);

Or

return ValidationProblem(new ValidationProblemDetails(
    new Dictionary<string, string[]>
    {
        {"Password", new[] {"Password field is required."}}
    }));
weichch
  • 9,306
  • 1
  • 13
  • 25
0

Generally, we could use the Validation attributes to add the validation urls, then if the model is invalid, it will return the ModelState (which contains the specified key and the error message):

public class UserModel
{
    [Required]
    public string Username { get; set; }
    [Required]
    [StringLength(5)]
    public string EmailAddress { get; set; }
}

The API method as below:

[Route("api/[controller]")]
[ApiController]
public class ToDoController : ControllerBase
{
    [HttpPost("AddUser")]
    public IActionResult AddUser([FromBody] UserModel user)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        //the the Model is valid, 
        var isvalid = ModelState.IsValid;


        //Then, if you want to add some exteneral validation, and meet the invalid validation, you can add an if statement
        //if statement.
        // use AddModelError() method to add the new error to the model state.
        ModelState.AddModelError("UserId", "userId id required");
        
        return BadRequest(ModelState);

        //else statement return to the next page.
    }

Then, when access the API method with invalid data, the result as below:

enter image description here

If we access the API method with valid data and add the custom model error, the result as below:

enter image description here

Besides, you can also create a custom ValidationError model which contains the returned fields, then try to use the action filter to handle the Validation failure error response. More detail information, please refer my reply in thread: I need to return customized validation result (response) in validation attributes in ASP.Net core Web API.

Zhi Lv
  • 18,845
  • 1
  • 19
  • 30