加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何从HttpResponseMessage读取MultipartContent?

发布时间:2020-12-15 05:38:09 所属栏目:百科 来源:网络整理
导读:我有以下WebApi,它将MultipartContent返回给客户端,其中包含来自数据库的图像和一些附加数据: – public class PhotoController : ApiController{ public HttpResponseMessage GetPhoto(Int32 personId) { var service = new PhotoService(); var photo = s
我有以下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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读