繁体   English   中英

Web API中的MultipartContent响应

[英]MultipartContent response in Web API

我想有可能为Web API中的请求返回复杂的响应。 例如,我想返回带有一些复杂对象的流。 我试图用MultipartFormDataContent做到这一点:

    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 我可以通过调试器看到我的Web API方法如何返回此响应,但是在客户端,我遇到了一个错误:

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;

更新:尝试通过以下方式读取客户端的响应:

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

并得到了这个例外:

提供了无效的“ HttpContent”实例。 它没有以“ 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"
    }

我发现了错误。 我使用以下命令返回我的多部分内容:

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

因此它返回正确的响应,但是随后multipartContent内部的流将被处置,这就是问题的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM