Home > Software engineering >  How do I configure validation error details return content-type as application/problem json instead
How do I configure validation error details return content-type as application/problem json instead

Time:06-24

Currently when the validation type failed (here I am using data annotation ValidationAttribute), its content-type is application/json.

enter image description here

How do I configure it to return its content-type as application/problem json while maintaining the error details?

Here is my controller in NET 6 Web Api project.

[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
    private readonly IAccountService _accountService;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="accountService"></param>
    public AccountController(IAccountService accountService)
    {
        _accountService = accountService;
    }

    [HttpGet]
    [Route("IsAccountClosed/{nric}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public async Task<ActionResult> IsAccountClosed([Required] string nric)
    {
        if (!ModelState.IsValid) {
            return UnprocessableEntity(ModelState);
        }     
    }
}

I tried to remove the ModelState parameter in UnprocessableEntity to become return UnprocessableEntity();

But I can't see the data annotation validation details.

enter image description here

Is it because of my ValidationFilterAttribute?

public class ValidationFilterAttribute : IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
           context.Result = new UnprocessableEntityObjectResult(context.ModelState);                
        }
    }

    public void OnActionExecuted(ActionExecutedContext context) { }
}

CodePudding user response:

is marked as required. so we have to pass always something

enter image description here

so I tried with space and call the API

and i am getting correct response with no change in your code.

enter image description here

check the response content type and also annotation validation detail is mentioned.

CodePudding user response:

You don't need that custom filter.
The ApiControllerAttribute triggers ModelState validation automatically.

From the documentation

The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:

if (!ModelState.IsValid)
{
    return BadRequest(ModelState);
}

So just remove that custom filter and ModelState.IsValid call.

  • Related