我有一个.Net Core 3.1 Web API,它需要与外部服务交互,该服务从WCF服务提供多部分/相关响应,并在上下文中包含附件,如下面的块。
HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 1790633
Content-Type: multipart/related; type="text/xml"; start="<8fb5b3efa6474add9032cb80870dc065>"; boundary="------=_Part_20200731120159.494997"
Server: Microsoft-IIS/10.0
Set-Cookie: ASP.NET_SessionId=jga2opbhoirgnhjhmmsuxi1k; path=/; HttpOnly; SameSite=Lax
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=f7b4f7f5d8cbd8c8bc5d9a4bf49e8b5938412c4294f6e2c2b5c2d5cfc4b4d437;Path=/;HttpOnly;Domain=lparouterpoc.azurewebsites.net
Date: Fri, 31 Jul 2020 13:33:04 GMT
--------=_Part_20200731120159.494997
Content-Type: text/xml; charset=UTF-8
Content-Transfer-Encoding: binary
Content-Id: <8fb5b3efa6474add9032cb80870dc065>
<?xml version="1.0" encoding="iso-8859-1"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
...
</SOAP-ENV:Envelope>
--------=_Part_20200731120159.494997
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-Id: 7b1fff220df5@xxxxx
%PDF-1.5
%����
...
Additional characters added in here
...
%%EOF
--------=_Part_20200731120159.494997
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-Id: 844eb478dc05@xxxxx
%PDF-1.5
...
Additional characters added here
...
%%EOF
--------=_Part_20200731120159.494997--
使用SOAPUI,我看到有附件,但每个附件都是空白的PDF。
.Net Core API中的代码是
using (var response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
var stream = await response.Content.ReadAsStreamAsync();
using var streamReader = new StreamReader(stream, Encoding.UTF8);
var message = await streamReader.ReadToEndAsync(); // This is where output is changed to add additional characters
var headers = response.Headers;
return new customResponse
{
ContentResult = new ContentResult
{
Content = message,
ContentType = response.Content.Headers.ContentType?.ToString(),
StatusCode = (int)response.StatusCode
},
ResponseHeaders = headers
};
}
下面的图片显示了一个例子,其中额外的字符是进来导致PDF的无效\损坏\空白。
其附加特征是内容长度从1021690到1790633。
我已经能够调试它到目前为止,并测试,文件之前,他们进入消息(字符串)是正确的,因为我能够读取多部分内容,并写入文件到磁盘时,检查文件确实是正确的使用
var content = await response.Content.ReadAsMultipartAsync();
for (var i = 0; i < content.Contents.Count; i++)
{
var item = content.Contents[i];
if (item.Headers.ContentType.ToString() == "application/octet-stream")
{
var bytes = await item.ReadAsByteArrayAsync();
File.WriteAllBytes(@$"c:\temp\{i}.pdf", bytes);
}
}
然后遍历content.Contents
。
如果有人能告诉我这是怎么发生的,我将不胜感激,我怎样才能阻止它的发生
进一步的调查和假设是,这可能是编码的问题吗?附件的WCF服务是TransferEncoding =“binary”
左边和中间的图像是相同的,中间写到磁盘直接从我的API(不是我需要的)向我表明,该文件可以读取和写入。
右边是服务的直接输出,它返回到SOAPUI并按预期下载。
当在监 windows 口中查看响应时,传输编码是空的,所以我对如何解决这个问题有点困惑。
2条答案
按热度按时间u3r8eeie1#
试试这个,
然后在你的控制器里像这样返回
gg0vcinb2#
在我的例子中,response有这样的header:
所以我不得不使用
BrotliStream
(.Net 5)参见:How do I decode an encoded HttpWebResponse?