4

I am using and Web API to perform some task, and when the task is finished the API return me a object in the OK method.

The code:

[Route("upload")]
[HttpPost]
public async Task<IHttpActionResult> PostFormData()
{
    //Create the object
    var blob = new BlobUploadModel();

    //Do some tasks
    ...

    //Return
    return Ok(blob);
}

How can I get this blob object in the response which, I think, should be a IHttpActionResult?

Any help is appreciated!

de li
  • 882
  • 1
  • 13
  • 25

1 Answers1

3

Web API will serialize your instance of BlobUploadModel into the MIME type specified in the client request Accept: header. The serialized blob will then be attached to the response body.

Your client that calls this action will need to deserialize the contents of the response body back to a BlobUploadModel. JSON.Net is a great library for serialization/deserialization between JSON objects and CLR objects. To deserialize a JSON response back to a BlobUploadModel using JSON.Net you can use the following:

 var blob = JsonConvert.DeserializeObject<BlobUploadModel>(responseBody);

Keep in mind that your client project will need to know what a BlobUploadModel is.

JTW
  • 3,546
  • 8
  • 35
  • 49
  • Thanks for your reply. I've got some further questions. If the object is serialized into XML format, will the JSON library still work? And How can I get this responseBody as a string? For now, I got the response as a var, should I just cast it to a string? – de li Aug 02 '15 at 13:35
  • If you're working with XML, you'll want to use an XML library like System.Xml.Serialization. This link shows a good example of deserialization with this library: https://msdn.microsoft.com/en-us/library/tz8csy73(v=vs.110).aspx. Regarding how to get the response as a string, it will depend on your HTTP client and how you're using it, but in most cases it will already be a string, so var will simply evaluate to string at runtime. – JTW Aug 02 '15 at 14:02
  • Similar question: http://stackoverflow.com/questions/30002936/how-to-get-the-object-from-httpactionresult-ok-method-web-api/30002975#30002975 – ThePatelGuy Feb 07 '17 at 19:46