c# - 如何从 HttpResponseMessage 读取 MultipartContent?

标签 c# .net asp.net-web-api

我有以下 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 浏览器。

最佳答案

首先你需要添加对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(); 

关于c# - 如何从 HttpResponseMessage 读取 MultipartContent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15088390/

相关文章:

.net - 将 RavenDb 移动到另一台服务器

angularjs - 如何在 adal-angular 的 httpinterceptor 发送的承载中添加声明

C# Excel 工作表对象引用未设置为对象的实例

c# - 身份服务器单点注销,也从服务器注销

c# - 两个表的 Fluent Nhibernate 映射一对多在映射中使用唯一而不是主键

c# - 模拟服务和网络位置的问题

c# - 如何将 Observable 值路由到不同的订阅者?

c# - 多个可选的查询字符串参数 REST API GET

asp.net - Webapi、Webhost 和 Owin 之间的关系

c# - C# 中有函数类型吗?