5

我有以下 WebApi,它将 MultipartContent 返回到客户端,其中包含来自数据库的图像和一些附加数据:-

    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;
    }
}

在客户端,HttpResponseMessage.Content 显示为 StreamContent 类型。如何以 MultipartContent 的形式访问它?客户端是 WPF - 不是 Web 浏览器。

4

2 回答 2

7

首先,您需要添加对System.Net.Http.Formatting,

然后您将可以访问扩展方法.ReadAsMultipartAsync()

示例

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(); 
于 2016-05-09T13:50:12.463 回答
0

您可以使用HttpContentMultipartExtensions中的辅助方法来读取客户端的内容。

于 2013-02-26T17:54:25.503 回答