Turn Httpresponsemessage return to JSON

Asked

Viewed 1,150 times

0

My API currently returns database values in JSON.

If no value is found, I return one HttpResponseMessage with error code 404.

However, when testing the request, only the message contained in Content is presented.

I would like to return all values filled in (Content, StatusCode and ReasonPhrase) JSON style (key-value).

That’s possible?

[HttpGet]
[Route("user/")]
public List<user> Get()
{
    new UserController();
    IQueryable<user> users = from itens in db.user select itens;
    if (!users.Any())
    {
        HttpResponseMessage error = new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent(string.Format("Nenhum usuário encontrado")),
            StatusCode = HttpStatusCode.NotFound,
            ReasonPhrase = "User Not Found"
            };
            throw new HttpResponseException(error);
        }
        return users.ToList();
    }
}
  • StatusCode and ReasonPhrase are part of the answer header. If you want this to be part of the body you will have to concatenate the values into Content or personalize the response.

  • @LINQ thanks for the reply. I saw that it is possible through your reply, but my little experience tells me that maybe it is not the best way. How is this treatment made in production?

  • I never made use of the header values in a JSON, because it is always possible to recover these values on the client side. Wouldn’t it be better to just change the rule in the client application?

  • We have not yet implemented the receipt of data in the client. The test was conducted via Postman. I believe that with this content I can follow. Thanks for the info. I could edit the comment as a reply?

1 answer

2


StatusCode and ReasonPhrase are part of the answer header. If you want this to be part of the body you will have to concatenate the values into Content or personalize the response.

Maybe you should rethink this need a little bit, since the response header will always be available to the client (the application that consumes the API) access.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.