尝试发送此多部分SOAP请求以及Web服务的附件

时间:2019-03-11 15:44:42

标签: c# .net soap webrequest mtom

我正在尝试提供一个接受多部分附件的基于SOAP的MTOM服务。这是我从C#创建请求的方式:

var request = (HttpWebRequest)WebRequest.Create("...skipping URL...");
request.ContentType = @"multipart/related;charset=""UTF-8"";type=""application/xop+xml"";start=""<http://tempuri.org/0>"";boundary=""uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1"";start-info=""application/soap+xml""";
request.Method = "POST";
request.Timeout = 30000;
request.Headers.Add("MIME-Version", "1.0");
request.Headers.Add("Accept-Encoding", "gzip, deflate");

var postData = @"--uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1
Content-ID: <http://tempuri.org/0>
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type=""text/xml""

[Skipping the SOAP envelope that goes here...]

--uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1
Content-ID: <http://tempuri.org/1/636875796573424479>
Content-Transfer-Encoding: binary
Content-Type: application/octet-stream

" + Encoding.UTF8.GetString(File.ReadAllBytes(@"C:\Users\User\Desktop\Sample.pdf")) + @"

--uuid:f276e990-75d0-4b5d-a0fd-e00a096e30ce+id=1--";

using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
    writer.Write(postData);

我的问题是:由于我知道内容类型必须是application / octet-stream,并且传输编码必须是二进制,因此我是否正确读取PDF文件的二进制数据以提交给该服务?在此处使用Encoding.UTF8.GetString(File.ReadAllBytes(@"C:\Users\User\Desktop\Sample.pdf"))是正确的还是错误的?我应该如何创建发送附件的请求?

编辑:这样做会更正确吗?

using (var stream = request.GetRequestStream())
using (var writer = new StreamWriter(stream))
using (var attachment = new FileStream(@"C:\Users\User\Desktop\Sample.pdf", FileMode.Open, FileAccess.Read))
{
    writer.Write(postDataPrefix); // Add everything up to the start of the attachment binary. 
    writer.Flush();
    stream.Flush();
    attachment.CopyTo(stream); // Add the actual attachment binary.
    writer.Flush();
    stream.Flush();
    writer.Write(postDataSuffix); // Add everything after the attachment binary.
    writer.Flush();
    stream.Flush();
}

0 个答案:

没有答案