0

I would like to return an HTTP status code & error message from a PUT method of an ApiController.

I have created an error class:

public class ErrorInformation
{
    public string Message { get; set; }
    public DateTime ErrorDate { get; set; }
}

and in the Put method I return this:

return new ResponseMessageResult(Request.CreateResponse(HttpStatusCode.NotModified,
                    new ErrorInformation { Message = "We apologize but an unexpected error occured. Please try again later.", ErrorDate = DateTime.UtcNow }));

When the status code is, say:

HttpStatusCode.OK or HttpStatusCode.InternalServerError - the caller gets the object in the response. But when it is HttpStatusCode.NotModified - only the status code is returned.

Why is this - and how can I ensure both my object and the status code are always returned?

thx.

niico
  • 11,206
  • 23
  • 78
  • 161
  • This is not valid use of "Not Modified" status code anyway, especially with the message like ""We apologize but an unexpected error occured. Please try again later." – Evk Feb 27 '17 at 17:44

2 Answers2

4

According to the HTTP specification, a 304 "not modified" response is not allowed to have a response body:

The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.

Source: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5

crates_barrels
  • 988
  • 13
  • 15
  • Thanks - I was thinking of using this error code when a PUT has data that fails validation (eg a field is of the wrong type, too short, missing etc). Which code would you recommend for that scenario? (the number available is huge - hard to pin one down). – niico Feb 27 '17 at 18:51
  • I guess looking here - http://stackoverflow.com/questions/3290182/rest-http-status-codes-for-failed-validation-or-invalid-duplicate - 400 would be best? – niico Feb 27 '17 at 19:04
  • 1
    Yes, I believe in your case a 400 "Bad request" is appropriate. Because it's definitely a client error, use a status code in the 4xx range. 3xx codes are mostly for redirection. – crates_barrels Feb 28 '17 at 09:54
0

In addition to the answer by @crates_barrels, I should day that it is definitely looks like Internal Server Error to me. If you have some kind of conflict, then you can use a special Conflict response in here. So I suggest that you check up the status codes and how they are used, e.g. in wiki. Then you can try to apply them in a best way to your scenario.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207