2016-07-26 41 views
1

我希望能够在Web API中返回对请求的复杂响应。例如,我想用一些复杂的对象返回流。 我试着用MultipartFormDataContent做到这一点:Web API中的Multipart内容响应

public static HttpResponseMessage GetMultipartResponse<T>(T responseData, Stream streamToReturn) 
    { 
     return new HttpResponseMessage 
     { 
      Content = new MultipartContent 
      { 
       new StreamContent(streamToReturn), 
       new ObjectContent<T>(responseData, new JsonMediaTypeFormatter()) 
      } 
     }; 
    } 

我得在服务器端正常HttpResponseMessage。我可以用我的调试器API的Web方法如何返回此响应见,但在客户端上我得到了一个错误:

StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
    Pragma: no-cache 
    X-SourceFiles: =?UTF-8?B?YzpcdXNlcnNccnVzdGFtX3NhbGFraHV0ZGlub3ZcZG9jdW1lbnRzXHZpc3VhbCBzdHVkaW8gMjAxM1xQcm9qZWN0c1xGaWxlU2VydmljZUFQSVxGaWxlU2VydmljZUFQSVxhcGlcZ2V0?= 
    Cache-Control: no-cache 
    Date: Tue, 26 Jul 2016 08:30:22 GMT 
    Server: Microsoft-IIS/8.0 
    X-AspNet-Version: 4.0.30319 
    X-Powered-By: ASP.NET 
    Content-Length: 1444 
    Content-Type: application/json; charset=utf-8 
    Expires: -1 
} 

有客户端或服务器端没有其他异常,我无法得到一些与导通错误详细信息

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; 

UPDATE: 尝试读取与在客户端响应:

var result = await response.Content.ReadAsMultipartAsync(); 

并得到了这个例外:

Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'.

我在哪里出错了?

更新2: 我有在服务器端正常响应:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.MultipartContent, Headers: 
    { 
     Content-Type: multipart/multipart; boundary="3e6d3573-9031-41a7-b7f4-d1421bc1451d" 
    } 

回答

0

我发现的错误。我回到我的多内容里面使用:

 using (var stream = MyFileStream()) 
     { 
      var respone = MultipartResponseHelper.GetMultipartResponse(response, stream, Request); 
      return respone; 
     } 

所以它返回正确的反应,但随后流内部multipartContent将设置这是问题的原因。