Home > Back-end >  In .Net 6 Web Api How to pass data to Json data to NotFound()
In .Net 6 Web Api How to pass data to Json data to NotFound()

Time:08-25

I am new to .Net 6 Web API, and I am trying to learn. I build a dummy app that you can add and retrieve city. Currently, when I send an id to find a city. If the idea does not exist I return the NotFound(), and the response looks like

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
    "title": "Not Found",
    "status": 404,
    "traceId": "00-48573a8a76307babb35bad289828ef16-0bdc7cccfcfee10c-00"
}

But when I sent extra information to the NotFound($"City with Id={id} is not found") I get the response like a string.

Is there a way to use NotFound(pass data) and get a response like similar to original response plus a property "Error": "city with id = 3 is not found"

{
    "Error": "city with id = 3 is not found"
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.4",
    "title": "Not Found",
    "status": 404,
    "traceId": "00-48573a8a76307babb35bad289828ef16-0bdc7cccfcfee10c-00"
}

Thank you for your help.

CodePudding user response:

It is not the best idea to return 404 NotFound if you can't find some data. It confuses the users since 404 NotFound is usually returned by .NET if the URL is not found.

I highly recommend you to use something else in this case - BadRequest for example. And you can create any JSON you want, if you don't like a string

return BadRequest( new
{
    Error = "city with id = 3 is not found",
    Title = "Record is not found",
    Status = 400
});

It is also a good idea to check the response code, before trying to extract data from API. In this case, the response code could be 400, but certainly not 404.

  • Related