How to read MultipartContent from HttpResponseMessage?

I have the following WebApi that returns MultipartContent to a client containing an image from a database and some extra 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, HttpResponseMessage.Content is displayed as a StreamContent type. How can I access it as a MultipartContent? The client is WPF, not a web browser.

+5
source share
2 answers

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

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

An 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(); 
+1
source

You can use helper methods in HttpContentMultipartExtensions to read client-side content.

0

All Articles