Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read MultipartContent from HttpResponseMessage?

I have the following WebApi which returns MultipartContent to the client containing an image from a database and a bit of additional data:-

    public class PhotoController : ApiController
{

    public HttpResponseMessage GetPhoto(Int32 personId)
    {
        var service = new PhotoService();
        var photo = service.SelectPrimaryPhoto(personId);
        if (photo == null)
            return Request.CreateResponse(HttpStatusCode.NoContent);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
        var content = new MultipartContent();
        content.Add(new ObjectContent<Photo.Data>(photo, new JsonMediaTypeFormatter()));
        content.Add(new StreamContent(photo.Image));
        response.Content = content;
        return response;
    }
}

On the client, the HttpResponseMessage.Content is surfaced as type StreamContent. How can I access it as MultipartContent? The client is WPF - not a Web Browser.

like image 416
Orac Avatar asked Feb 26 '13 11:02

Orac


1 Answers

First you need to add a reference to System.Net.Http.Formatting,

then you will have access to the extension method .ReadAsMultipartAsync().

Example:

using System.Net.Http.Formatting;

// ...

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsyc("{send the request to api}");

var content = await response.Content.ReadAsMultipartAsync();

var stringContent = await content.Contents[0].ReadAsStringAsync();
var streamContent = await content.Contents[1].ReadAsStreamAsync(); 
like image 70
A-Sharabiani Avatar answered Sep 28 '22 06:09

A-Sharabiani