asp.net-coreasp.net-web-apihttp-status-codeshttp-status-code-204

ASP.NET Core Web API - Return a string message with a NoContent Response?


I have some records in the database that may or may not have some information for a certain column, and that's OK.

If a consumer of the endpoint runs into one of these records, I'd like to return "NoContent", because, well, there's No Content for that record that we can execute on. BUT ... I'd like to give them a message why, as there are two distinct reasons.

When looking at other status codes, this works:

return Accepted("I SEE THIS STRING!");

It actually shows up in the Response Header as the field location (I think, don't make me run this project again!)

This works for say Internal Server error:

return StatusCode(500, "I SEE THIS TOO!");

But, for NoContent there is no constructor like Accepted, where you can pass an object. Also, this shows me no string whatsoever:

return StatusCode(204, "WHY CAN'T I SEE THIS STRING?!");

Help!


Solution

  • 204 (No Content) returns an HttpResponseMessage with, well, No Content.

    If you do have content to return that the user can consume (the two reasons), then you don't have a No Content scenario.

    Perhaps an Ok (200) with a custom ContentNotProvided class that holds a message, which can be consumed by the client, will do the trick?

    Alternatively, return a BadRequest (400) with a message.