0

According to this blog post, I can create an error response in my ApiController, that provides useful information to the client, like this:

    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format("Contact {0} not found.", id)));

... and the client will receive an "object" containing the error details along with the (in this example) 404 status:

{
     "Message": "Contact 22 not found.",
     "MessageDetail": "<other info - not always present>"
}

(I don't think that MessageDetail is appropriate in this example, and so would probably not be included, but under other circumstances it might be - see the blog post).

Sounds great, but how should my C# client-side application consume this on the client side? I made a request, I was expecting a JSON-encoded Contact object in response, but instead I got a different type of object.

Because the response code indicated a failure, then I guess I know not to expect the Contact object, and to look instead for this error object. But given that not every error will return one of these, and also given that the MessageDetail member may or may not be present, how do I go about parsing the response? (Note: in my scenario, it'll be JSON-encoded, and I'm using JSON.NET on the client side).

If the object was of a well-known type, then I could just use JsonConvert.DeserializeObject<T>(), but I don't think there's a pre-defined type, and if I create my own class what do I do about the optional MessageDetail member?

I'm not very familiar with processing JSON, so this may be obvious to those who are - in which case all advice gratefully received.

4

1 回答 1

3

HttpError is deserializable from client side. You can use it to read the data from error response.

于 2012-09-25T09:06:00.943 回答