How to read MultipartContent from HttpResponseMessage?
我有以下WebApi将MultipartContent返回到客户端,该客户端包含来自数据库的图像和一些附加数据:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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浏览器。
首先,您需要添加对
的引用
然后您将可以访问扩展方法
示例:
1 2 3 4 5 6 7 8 9 10 11 | 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(); |
您可以使用HttpContentMultipartExtensions中的帮助方法来读取客户端上的内容。