On the server I have:
string errorMessage = string.Format("Error: the following employeee has an invalid department: {0} {1}", new[] { employeeWithMissingDepartment.Id.ToString(), employeeWithMissingDepartment.Name });
return BadRequest(errorMessage);
As you can see I am sending the error description in the BadRequest
.
On the client I do the following:
HttpResponseMessage response = this.PostAsJsonAsync<T>("api/controller/action", parameter).Result;
if(!response.IsSuccessStatusCode)
{
error= response.ReasonPhrase;
}
In this case the error variable only gets "BadRequest" and not the descriptive error message that I made, how do I get the error message in BadRequest
?
Both responses (HTTP OK and BadRequest responses) send the message in a different way. YES well both send in the body of the Message
UNIT 1: Reason Phrase (HTTP)
First of all a clarification about ReasonPhrase which is the description (in English) of the http command... just to make the code more "human". examples
TOPIC 2: Response message in WebAPI with Response OK & BadRequest?
Let's take an example of an OK response where it sends the message. In the Content property of the response (the response is of type OkNegotiatedContentResult)
IF we see the response for a BadRequest response (of type BadRequestErrorMessageResult) we see that the property that is set is Message
As we see above then, both support sending "messages" but they are two different properties. If you are going to use BAdRequest you need to know this.
TOPIC 3: How do you serialize (how is the response)?
And how to read that answer! Well the OK returns in the content of the response (plain text). But BadRequest serializes to an object that has a Message property
So you should keep this in mind to get the message
I hope it helps or guides you.
Links that may help you
It is simply obtained like this:
It's the same as when you return an Ok 200.