IRS-A2A BulkRequestTransmitter消息无法正常formmatted和/或不能PTED间$ P $ [英] IRS-A2A BulkRequestTransmitter message not formmatted properly and/or cannot be interpreted

查看:446
本文介绍了IRS-A2A BulkRequestTransmitter消息无法正常formmatted和/或不能PTED间$ P $的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过BulkRequestTransmitter Web服务提交时,收到以下错误。构图指南小于尽可能有益,因为此消息的推移,当我比较我的SOAP XML从构图指南SOAP,他们似乎是苹果对苹果。我希望另一双眼睛或许能够看到问题的所在。


  

未正确格式化的消息和/或不能被除preTED。请检查在AIR提交​​组成和参考指南位于<一第3节中列出的XML标准href=\"https://www.irs.gov/for-Tax-Pros/Software-Developers/Information-Returns/Affordable-Care-Act-Information-Return-AIR-Program\" rel=\"nofollow\">https://www.irs.gov/for-Tax-Pros/Software-Developers/Information-Returns/Affordable-Care-Act-Information-Return-AIR-Program,纠正问题,然后重试。


我已经试过:


  • 试图用(无需)在SOAP信封空白提交。

  • 已尝试采用XML格式的表单数据XML提交。

  • 试图与表单数据提交 base64string 格式(因为这是提交)。

  • 新增了 DS preFIX的标志性元素。二手这是为了给preFIX添加到签名元素,因此帖子

  • 在pretty打印格式,并根据更新的成分指南(V4.2)新增表单数据。

  • 复制的格式的 MIME 在节中描述的 BulkTransmitterService 要求 10.3 构图指南。

  • 创建了两个解决方案:1)手动创建的SOAP请求所必需的XML,并通过的HttpWebRequest 对象发送; 2)发送通过提交请求 WSDL 导入到项目作为服务参考,使用自定义连接codeRS为 gzip和MTOM编码键,手动创建必要的SOAP状态请求的XML(通过的HttpWebRequest 发送)。

更新#1 结果
更新基于一些新增加的要求。


  • 新增了 DS preFIX的标志性元素。

  • 在pretty打印格式,并根据更新的成分指南新增表单数据。(V4.2:5.4.2节)

更新#2 结果
我开始Visual Studio中导入架构引用必要的新实例中手动创建 SOAP .xml文件。的我这样做是任何类型的应用程序创建的的外面。

在这样做,我能找到在 SOAP 我创建通过我的应用程序的一些额外的bug(谢谢你的智能感知!)。我发现的臭虫的清单XML中,因为他们不符合国税局的模式。

我将寻找到这些,在未来24小时,相应的更新。


  • 金塔:MailingAddressGrp 应该要么瓮子:USAddressGrp 金塔:ForeignAddressGrp 。那么孩子应该包含正确的地址元素。我的code目前缺少瓮的直接子:MailingAddressGrp

  • urn1值: Form1094C_Request_的DocumentSystemFileNm [TCC] _yyyyMMddThhmmssfffZ.xml 不正确。我不能完全确定它应该是什么,只是还没有。

  • urn1:BulkExchangeFile 元素,是有相关的 XOP一个问题:包括元素我有内。该模式想要一个base64Binary的类型。

更新#2.5


  • 更新我的XML生成过程包括 USAddressGrp 元素。

  • 发现,我曾在毫秒一个额外的字符(四改三)。一旦我纠正这一点,从文件名的开头删除字符串表一起,为 urn1值:DocumentSystemFileNm 能够根据模式验证成功。

更新#3


  • 更新基于我所作出的更新完整的请求。在这
    一点,我无法推断出什么是错我的要求。如果
    任何人看到什么明显的,请大家帮忙!

更新#4


  • 更新的基础上做了补充更新完整的请求。去除
    DS preFIX从基于另一个SO用户的签名
    反馈。此用户已经得到了这些要求,而无需工作
    在事后的 DS preFIX追加到签名和
    重新计算签名

    所谓的用户也证实了他的请求与工作
    &LT; INC:包括&GT; 元素被设置为的子元素
    &LT; BulkExchangeFile方式&gt; 元素


  • 确认了 MIME 标题是正确的,因为每个样品中的成分指南的10.3节。

更新#5


  • 我目前有两种解决方案:一种是手动发送创造必要的XML的SOAP请求,并通过的HttpWebRequest 发送;而其中一个是使用 WSDL服务引用为提交申请,使用自定义连接codeRS概述如下,并手动创造必要的SOAP请求的XML状态。

    由于本次更新中,方案一给我制作提交请求时,上述错误,并给我制定的状态请求时,下面的错误。但是,使用方案二,这两项要求(投稿和状态)时,给我下面的错误。

    我期待到可能的证书问题,看看他们在与这两种解决方案的任何进展。


更新#6

有一些问题,我跑这引起了我被延迟。我就不告诉你具体细节,不过,短期的是,我们没有与美国国税局系统中注册的安全证书,也没有我们有正确安装了证书,这样我可以通过访问信息的X509Store 。最后,这些东西得到了做,我是能够测试从服务器(与我LOCALMACHINE它没有适当的证书)数据提交给IRS。不幸的是,我仍然接受下文详述的WS-Security的错误。我已经更新了什么,我目前正在发送完整的请求。


  

这是发生错误与消息:WS安全标头的消息中是无效的。请检查在AIR提交​​组成和参考指南位于<一节5概述的传输指令href=\"https://www.irs.gov/for-Tax-Pros/Software-Developers/Information-Returns/Affordable-Care-Act-Information-Return-AIR-Program\" rel=\"nofollow\">https://www.irs.gov/for-Tax-Pros/Software-Developers/Information-Returns/Affordable-Care-Act-Information-Return-AIR-Program,纠正问题,然后重试。



的MIME头所有的换是原样,我相信换行符的期望是什么。
的FORMDATA附件发送为pretty打印,而SOAP信封不大;在这个岗位SOAP信封的格式以提高可读性。

更新#7:

由于用户:jstill和fatherOfWine与他们有什么贴在下面,并为苯教在这个项目上较早的援助。我已经经历了一面墙在获得提交工作打破。它现在的工作。状态请求也在努力。不过,我需要弄清楚如何处理它,以拉状态和附件(错误数据文件)出来。

完整的请求:

 内容编码:gzip
接受编码:gzip,紧缩
内容类型:多部分/相关;类型=应用程序/ XOP + XML;开始=&所述; rootpart&gt;中;启动信息=文/ XML;边界=MIME_boundary
SOAPAction报:BulkRequestTransmitter
MIME-版本:1.0
主持人:la.www4.irs.gov--MIME_Boundary
内容类型:应用程序/ XOP + xml的;字符集= UTF-8;类型=文/ XML
内容传输编码:8位
内容编号:LT; root_part&GT;&LT; S:信封的xmlns:S =htt​​p://schemas.xmlsoap.org/soap/envelope/&GT;
    &LT; S:页眉和GT;
        &LT;安全的xmlns:H =htt​​p://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd的xmlns =HTTP://docs.oasis -open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd的xmlns:XSI =http://www.w3.org/2001/XMLSchema-instance的xmlns:XSD = http://www.w3.org/2001/XMLSchema\">
            &LT;签名ID =SIG-E77c57b78ebc54e989bfc9e43604a04a4的xmlns =htt​​p://www.w3.org/2000/09/xmldsig#&GT;
                &LT;&的SignedInfo GT;
                    &LT; CanonicalizationMethod的算法=htt​​p://www.w3.org/2001/10/xml-exc-c14n#WithComments/&GT;
                    &LT;是SignatureMethod算法=htt​​p://www.w3.org/2000/09/xmldsig#rsa-sha1/&GT;
                    &lt;参考URI =#TS-Eb4799bee41bb4df0a72f52832d283ef7&GT;
                        &LT; D​​igestMethod算法=htt​​p://www.w3.org/2000/09/xmldsig#sha1/&GT;
                        &LT;&的DigestValue GT; TimestampDigestValue] LT; /&的DigestValue GT;
                    &LT; /参考和GT;
                    &lt;参考URI =#标识-E5f1ed32aab8f4578adeee5debd851a62&GT;
                        &LT; D​​igestMethod算法=htt​​p://www.w3.org/2000/09/xmldsig#sha1/&GT;
                        &LT;&的DigestValue GT; ACABusinessHeaderDigestValue] LT; /&的DigestValue GT;
                    &LT; /参考和GT;
                    &lt;参考URI =#标识-E4a71164001994d7f865fc7ddb8055350&GT;
                        &LT; D​​igestMethod算法=htt​​p://www.w3.org/2000/09/xmldsig#sha1/&GT;
                        &LT;&的DigestValue GT; ManifestDigestValue] LT; /&的DigestValue GT;
                    &LT; /参考和GT;
                &LT; /&的SignedInfo GT;
                &LT;&SignatureValue所GT;的SignatureValue] LT; /&的SignatureValue GT;
                &LT;密钥信息n =KI-E2309cb142e1a4076a2e71373e6e6b75f&GT;
                    &LT; SecurityTokenReference d6p1:ID =STR-E2751169ee468470290fe5e8bfb34589e的xmlns:d6p1 =htt​​p://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd的xmlns =htt​​p://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&GT;
                        &LT; KeyIdentifier EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\" ValueType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\">[KeyIdentifier]</KeyIdentifier>
                    &LT; / SecurityTokenReference&GT;
                &LT; /密钥信息&GT;
            &LT; /签署及GT;
            &LT; A:时间戳的:ID =TS-Eb4799bee41bb4df0a72f52832d283ef7的xmlns =htt​​p://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd的xmlns为:a =htt​​p://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&GT;
                &LT; A:创建&GT; 2016-05-18T09:51:05.856Z&LT; / A:创建&GT;
                &LT; A:过期&GT; 2016-05-18T10:01:05.856Z&LT; / A:过期&GT;
            &LT; / A:时间戳&GT;
        &LT; /安全和GT;
        &LT; ACATransmitterManifestReqDtl答:ID =ID-E4a71164001994d7f865fc7ddb8055350的xmlns:H =瓮:我们:政府网站:财政部:IRS:分机:ACA:空气:7.0的xmlns:A =HTTP://docs.oasis-open。组织/ WSS / 2004/01 /绿洲-200401-WSS-wssecurity型多功能1.0.xsd的xmlns =金塔:我们:政府网站:财政部:IRS:分机:ACA:空气:7.0&GT;
            &LT; PaymentYr&GT; 2015年&LT; / PaymentYr&GT;
            &所述; PriorYearDataInd大于0&下; / PriorYearDataInd&GT;
            &LT; EIN的xmlns =金塔:我们:政府网站:财政部:国税局:常见的&GT; 000000301&LT; / EIN&GT;
            &LT; TransmissionTypeCd≠0&LT; / TransmissionTypeCd&GT;
            &LT; TestFileCd&GT; T&LT; / TestFileCd&GT;
            &LT; OriginalReceiptId /&GT;
            &LT; TransmitterNameGrp&GT;
                &LT; BusinessNameLine1Txt /&GT;
            &LT; / TransmitterNameGrp&GT;
            &LT; CompanyInformationGrp&GT;
                &LT; CompanyNm&GT; Selitestthree&LT; / CompanyNm&GT;
                &LT; MailingAddressGrp&GT;
                    &LT; USAddressGrp&GT;
                        &LT; AddressLine1Txt&GT; 6689柳林院&LT; / AddressLine1Txt&GT;
                        &LT; CityNm的xmlns =金塔:我们:政府网站:财政部:国税局:常见的&GT;比佛利山庄&LT; / CityNm&GT;
                        &所述; USStateCd&GT; CA&下; / USStateCd&GT;
                        &LT; USZIPCd的xmlns =金塔:我们:政府网站:财政部:国税局:常见的&GT; 90211&LT; / USZIPCd&GT;
                    &LT; / USAddressGrp&GT;
                &LT; / MailingAddressGrp&GT;
                &LT; ContactNameGrp&GT;
                    &LT; PersonFirstNm&GT;玫瑰和LT; / PersonFirstNm&GT;
                    &LT; PersonLastNm&GT;林肯&LT; / PersonLastNm&GT;
                &LT; / ContactNameGrp&GT;
                &LT; ContactPhoneNum&GT; 5559876543&LT; / ContactPhoneNum&GT;
            &LT; / CompanyInformationGrp&GT;
            &LT; VendorInformationGrp&GT;
                &LT; VendorCd I标记&LT; / VendorCd&GT;
                &LT; ContactNameGrp&GT;
                    &LT; PersonFirstNm&GT; ContactFirstName&LT; / PersonFirstNm&GT;
                    &LT; PersonLastNm&GT; ContactLastName&LT; / PersonLastNm&GT;
                &LT; / ContactNameGrp&GT;
                &LT; ContactPhoneNum&GT; ContactPhoneNumber&LT; / ContactPhoneNum&GT;
            &LT; / VendorInformationGrp&GT;
            &所述; TotalPayeeRecordCnt→3&下; / TotalPayeeRecordCnt&GT;
            &所述; TotalPayerRecordCnt→1&下; / TotalPayerRecordCnt&GT;
            &LT; SoftwareId&GT;&PPACA LT; / SoftwareId&GT;
            &LT; FormTypeCd&GT; 1094 / 1095C&LT; / FormTypeCd&GT;
            &LT; BinaryFormatCd的xmlns =金塔:我们:政府网站:财政部:国税局:常见的&GT;应用/ XML&LT; / BinaryFormatCd&GT;
            &LT; ChecksumAugmentationNum xmlns=\"urn:us:gov:treasury:irs:common\">6b2512ce28f603f76261923d297738e5</ChecksumAugmentationNum>
            &LT; AttachmentByteSizeNum的xmlns =金塔:我们:政府网站:财政部:国税局:常见的&GT; 14076&LT; / AttachmentByteSizeNum&GT;
            &LT; D​​ocumentSystemFileNm&GT; 1094C_Request_ [TCC] _20160518T215105716Z.xml&LT; / DocumentSystemFileNm&GT;
        &LT; / ACATransmitterManifestReqDtl&GT;
        &LT; ACABusinessHeader答:ID =ID-E5f1ed32aab8f4578adeee5debd851a62的xmlns:H =瓮:我们:政府网站:财政部:IRS:消息:acabusinessheader的xmlns:A =htt​​p://docs.oasis-open.org/wss/ 2004/01 /绿洲-200401-WSS-wssecurity型多功能1.0.xsd的xmlns =金塔:我们:政府网站:财政部:IRS:消息:acabusinessheader&GT;
            &LT; UniqueTransmissionId xmlns=\"urn:us:gov:treasury:irs:ext:aca:air:7.0\">51958882-c653-4eab-8dfb-287ecc555aaa:SYS12:[TCC]::T</UniqueTransmissionId>
            &LT;时间戳的xmlns =金塔:我们:政府网站:财政部:国税局:常见的&GT; 2016-05-18T14:51:05.8568594-07:00&LT; /时间戳&GT;
        &LT; / ACABusinessHeader&GT;
    &LT; / S:页眉和GT;
    &LT; S:身体的xmlns:XSI =htt​​p://www.w3.org/2001/XMLSchema-instance的xmlns:XSD =htt​​p://www.w3.org/2001/XMLSchema&GT;
        &LT; ACABulkRequestTransmitter的xmlns =金塔:我们:政府网站:财政部:IRS:消息:irsacabulkrequesttransmitter版本=1.0&GT;
            &LT; BulkExchangeFile的xmlns =金塔:我们:政府网站:财政部:国税局:常见的&GT;
                &LT; INC:包括HREF =CID:1094C_Request_BB0S4_20160518T215105716Z.xml的xmlns:INC =htt​​p://www.w3.org/2004/08/xop/include/&GT;
            &LT; / BulkExchangeFile&GT;
        &LT; / ACABulkRequestTransmitter&GT;
    &LT; / S:身体与GT;
&LT; / S:信封&GT;--MIME_Boundary
内容类型:文本/ xml的;字符集= US-ASCII
内容传输编码:7位
内容编号:LT; 1094C_Request_BB0S4_20160518T215105716Z.xml&GT;
内容处置:附件; NAME =1094C_Request_ [TCC] _20160518T215105716Z.xml[prettyPrintFormDataXml]
--MIME_boundary--


解决方案

不知道这是否会解决您的问题,但尽管如此,我给它一个镜头。有时候,帮助来自非常意外来源:)


  1. 所有时间戳字段首先是在一个错误的格式:一个在
    businessheader不应包含毫秒的。我知道它
    一个事实。

  2. 在安全性头时间戳只允许3位重新present
    毫秒。

  3. 删除空的元素,比如从ACATransmitterManifestReqDtl元素OriginalReceiptId:他们不喜欢那些

  4. 我希望你为他们提供适当的软件ID,因为你拥有了它在有效载荷空的,但我相信他们会喜欢拥有它,恕我直言。)

  5. 我想你在响应中已经得到了消息,也有一些做与Signature元素。我认为他们要签名元素有一些preFIX(DSpreferably,我猜)。但在这里,我不知道100%。

    您看,我同样争夺战你。而我的信息安全时间戳有preFIXU型,他们不抱怨。虽然他们不喜欢的BinarySecurityToken永远。:)我奋力生成签名国税局喜好。 WCF是非常隐秘的,不便于preFIX对SOAP信封改变或允许选择CanonicalizationMethod的算法的签名。


更新:是能够成功地发送请求到服务。告诉你一次:prefixes是不重要的。什么是重要的:CorrectedInd标签必须在Form1095BUpstreamDetail present和属性记录类型=字符串LINENUM =0也必须是present。

UPDATE2
我已经改变了另一件事我已经放在ACABusinessHeader ManifestDtl之前。
这里是我的设置:我使用WCF为载体,SignedXml生成签名。另外我使用自定义的GZIP EN codeR(显而易见的reasons0和定制MtomEn codeR读取服务响应(是的,是的,它是MTOMed :))你能相信这些小宠物?!?!?)这不是一切:他们发送响应,多部分的文件,只有1份:)),我不得不调整我的EN codeR来处理!瞧,服务开始做人。希望它可以帮助。

UPDATE3
首先,使附件文件确保数据对应于你正在使用的豚鼠的测试场景。我,也许听起来像一个破纪录,但是这是非常重要的。
现在,我就砍了东西,present我有什么。这是一个有点粗糙,但它的伎俩。)

1.Here是配置文件部分:结果
1.1.Make确保system.serviceModel元素包含以下部分:

 &LT;附加功能,GT;
  &LT; bindingElementExtensions&GT;
    &LT;添加名称=gzipMessageEncodingTYPE =&LT; namespaceWhereEn coderLives&GT; .GZipMessageEncodingElement,GZipEn codeR,版本= 4.0.0.0,文化=中立,公钥=空/&GT;
  &LT; / bindingElementExtensions&GT;
&LT; /扩展&GT;

1.2。确保绑定元素包含此:

 &LT; customBinding&GT;
    &LT;绑定名称=BulkRequestTransmitterBinding&GT;
      &LT; gzipMessageEncoding innerMessageEncoding =textMessageEncoding/&GT;
      &LT; httpsTransport /&GT;
    &LT; /&结合GT;
  &LT; / customBinding&GT;

1.3。更改BulkRequestTransmitterPort endpoit结合客户元素下的customBinding(并更改绑定名字到自定义绑定以及名称),并确保它包含以下部分:

 &LT;同一性GT;
      &LT; D​​NS值=从证书域/&GT;
    &LT; /身份&GT;

此外客户端元素应该包含以下部分:

 &LT;&元GT;
    &LT; policyImporters&GT;
      &LT;外延式=NamespaceToToTheLocationOf.GZipMessageEncodingBindingElementImporter,GZipMessageEn codeR,版本= 1.0.0.0,文化=中立,公钥=空/&GT;
    &LT; / policyImporters&GT;
  &LT; /元&GT;

<醇开始=2>

  • 的GZip EN codeR你可以从以下链接获得:
    https://msdn.microsoft.com/en-美国/库/ cc138373(v = VS.90)的.aspx
    只需下载WCF的例子,呆滞项目下移至整个GZipMessageEn codeR项目。


  • 获取MTOMEn codeR(这是我从SwaEn codeR更名为清楚起见)从这个链接:
    肥皂与 - 附件
    将下面的类成GZipMessageEn codeR项目:

    MimeContent,MimeParser,MimePart,MTOMEn codeR


  • 修改GZipMessageEn codeR类是这样的:

    4.1。添加下面的类的开头code:

      // ------------------- MTOM相关的东西。开始。 ---------------------
        常量字符串ATTCHMNT_PROP =attachment_file_content;
        常量字符串ATTCHMNT_CONTENT_ID =这里所说的内容ID;    私人字符串_ContentType;
        私人字符串_MediaType;    保护MimeContent _MyContent;
        保护MimePart _SoapMimeContent;
        保护MimePart _AttachmentMimeContent;
        保护GZipMessageEn coderFactory _Factory;
        保护MimeParser _MimeParser;
        私人无效SetupMTOM(GZipMessageEn coderFactory厂)
        {
            //
            _ContentType =多部分/相关的;
            _MediaType = _ContentType;        //
            //创建拥有的对象
            //
            _Factory =厂;
            _MimeParser =新MimeParser();        //
            //为MIME内容的消息创建对象
            //
            _SoapMimeContent =新MimePart()
            {
                ContentTypeStart =应用程序/ XOP + XML,
                的ContentType =文本/ XML
                内容ID =这里所说的信封MIME ID从HTTP Content-Type头,// TODO:使内容ID动态的或可配置?
                字符集=UTF-8,// TODO:使字符集的配置?
                TransferEncoding =8位// TODO:让Transfer-Encoding的配置?
            };
            _AttachmentMimeContent =新MimePart()
            {
                的ContentType =应用程序/ XML,// TODO:AttachmentMimeContent.ContentType配置?
                内容ID = ATTCHMNT_CONTENT_ID,// TODO:AttachmentMimeContent.ContentId配置/动力?
                TransferEncoding =7位// TODO:AttachmentMimeContent.TransferEncoding动态/配置?
            };
            _MyContent =新MimeContent()
            {
                边界=这里有云边界标识// TODO:MimeContent.Boundary配置/动力?
           };
            _MyContent.Parts.Add(_SoapMimeContent);
            _MyContent.Parts.Add(_AttachmentMimeContent);
            _MyContent.SetAsStartPart(_SoapMimeContent);
        }
        // ------------------- MTOM相关的东西。结束。 ----------------------


  • 4.2。修改方法的WriteMessage(消息消息,INT maxMessageSize,BufferManager bufferManager,INT messageOffset)是这样的:

     公众覆盖ArraySegment&LT;位&GT;的WriteMessage(消息消息,INT maxMessageSize,BufferManager bufferManager,INT messageOffset)
            {
                ArraySegment&LT;位&GT;缓冲= innerEn coder.WriteMessage(消息,maxMessageSize,bufferManager,0);
                VAR requestSOAPEnvelopeXml = System.Text.Encoding.UTF8.GetString(buffer.Array);            //这里创建安全节点,并请求签名。外汇:
                requestSOAPEnvelopeXml = SigngEnvelope(requestSOAPEnvelopeXml);
                //这里你得到1094 \\ 1095的形式XML有效载荷。
                字符串fileContent = GetAttachmentFileContent();            //这里谈到的MTOMing ...
                _SoapMimeContent.Content = System.Text.Encoding.UTF8.GetBytes(requestSOAPEnvelopeXml);
                _AttachmentMimeContent.Content = System.Text.Encoding.UTF8.GetBytes(fileContent);            _MyContent.Parts.Where(M = GT; m.ContentId = NULL&放大器;!&安培; m.ContentId.Equals(ATTCHMNT_CONTENT_ID))单()ContentDisposition =用GetFileName(信封)。
                //现在为该流创建邮件内容
                字节[] = MimeContentBytes _MimeParser.SerializeMimeContent(_MyContent);
                INT MimeContentLength = MimeContentBytes.Length;            //写MIME内容到传入方法的缓冲区的部分
                字节[] = TargetBuffer bufferManager.TakeBuffer(MimeContentLength + messageOffset);
                Array.Copy(MimeContentBytes,0,TargetBuffer,messageOffset,MimeContentLength);            //返回缓冲器的段到框架
                返回的COM pressBuffer(新ArraySegment&LT;位&GT;(TargetBuffer,messageOffset,MimeContentLength),bufferManager,messageOffset);
            }

    4.3。覆盖夫妇更多的方法是这样的:

     公众覆盖信息ReadMessage(ArraySegment&LT;位&GT;缓冲区,BufferManager bufferManager,字符串的contentType)
            {
                ArraySegment&LT;位&GT; DECOM pressedBuffer = DECOM pressBuffer(缓冲,bufferManager);            MtomEn codeR mtomEn codeR =新MtomEn codeR(innerEn codeR,_Factory);
                消息returnMessage = mtomEn coder.ReadMessage(缓冲,bufferManager,则contentType);
                returnMessage.Properties.En codeR = mtomEn codeR;            返回returnMessage;
            }        公众覆盖布尔IsContentTypeSupported(字符串的contentType)
            {
                返回true;
            }

    4.4。确保GZipMessage构造是这样的:

     内部GZipMessageEn codeR(MessageEn codeR messageEn codeR,GZipMessageEn coderFactory厂)
                :基地()
            {
                如果(messageEn codeR == NULL)
                    抛出新的ArgumentNullException(messageEn codeR,恩codeR有效的信息必须传递给GZipEn codeR);
                innerEn codeR = messageEn codeR;            SetupMTOM(工厂);
            }

    5。确保GZipMessageEncodingBindingElement类有以下方法:

     公共覆盖无效ApplyConfiguration(BindingElement bindingElement)
        {
            GZipMessageEncodingBindingElement结合=(GZipMessageEncodingBindingElement)bindingElement;
            PropertyInformationCollection的PropertyInfo = this.ElementInformation.Properties;
            如果(的PropertyInfo [innerMessageEncoding。ValueOrigin!= PropertyValueOrigin.Default)
            {
                开关(this.InnerMessageEncoding)
                {
                    案textMessageEncoding:
                        binding.InnerMessageEncodingBindingElement =
                            新TextMessageEncodingBindingElement(MessageVersion.Soap11,Encoding.UTF8);
                        打破;
                    案binaryMessageEncoding:
                        binding.InnerMessageEncodingBindingElement =新BinaryMessageEncodingBindingElement();
                        打破;
                }
            }
        }

    <醇开始=6>

  • 修改MTOMEn codeR类。确保下面的方法是这样的:

     公众覆盖信息ReadMessage(的System.IO.Stream流,诠释maxSizeOfHeaders,字符串的contentType)
    {
        VerifyOperationContext();    如果(contentType.ToLower()。StartsWith(多部分/相关))
        {
            字节[] = ContentBytes新的字节[stream.Length]
            stream.Read(ContentBytes,0,ContentBytes.Length);
            MimeContent内容= _MimeParser.DeserializeMimeContent(co​​ntentType中,ContentBytes);        如果(Content.Parts.Count&GT; = 1)
            {
                MemoryStream的毫秒=新的MemoryStream(Content.Parts [0] .Content);
                //至少目前IRS发送SOAP信封的第一部分(多部分响应,只有一部分(原文如此!))为XML。
                信息MSG = ReadMessage(MS,int.MaxValue,文/ XML); // Content.Parts [0] .ContentType);            如果(Content.Parts.Count→1)
                    Msg.Properties.Add(ATTCHMNT_PROP,Content.Parts [1] .Content);            返回消息;
            }
            其他
            {
                抛出新ApplicationException的(!发送无效的MIME邮件带附件的SOAP是有道理的,只是,至少有2 MIME邮件内容的部件!);
            }
        }
        否则,如果(contentType.ToLower()。StartsWith(文/ XML))
        {
            读者的XmlReader = XmlReader.Create(流);
            返回Message.CreateMessage(读卡器,maxSizeOfHeaders,MessageVersion);
        }
        其他
        {
            抛出新ApplicationException的(
                的String.format(
                    阅读邮件内容类型无效:{0}支持的内容类型是多部分/相关和文本/ XML!
                    内容类型));
        }
    }


  • GZipMessageEn coderFactory类的构造函数应该是这样的:

     公共GZipMessageEn coderFactory(MessageEn coderFactory messageEn coderFactory)
    {
        如果(messageEn coderFactory == NULL)
            抛出新的ArgumentNullException(messageEn coderFactory,恩codeR工厂有效的信息必须传递给GZipEn codeR);
        EN codeR =新GZipMessageEn codeR(messageEn coderFactory.En codeR,这一点);
    }


  • 这是我如何调用该服务:

      VAR requestClient =新BulkRequestTransmitterPortTypeClient(BulkRequestTransmitterPort);        requestClient.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.None;
     #如果DEBUG
            变种VS = requestClient.Endpoint.Behaviors.Where((ⅰ)=方式&gt; i.GetType()Namespace.Contains(的VisualStudio));
            如果(VS!= NULL)
             requestClient.Endpoint.Behaviors.Remove((System.ServiceModel.Description.IEndpointBehavior)vs.Single());
    #万一
       使用(VAR范围=新OperationContextScope(requestClient.InnerChannel))
            {
                 //添加适当的HTTP标头传出requqest。
                HTT prequestMessageProperty requestMessage =新HTT prequestMessageProperty();            requestMessage.Headers [内容编码] =gzip的;
                requestMessage.Headers [的Content-Type] = @多部分/相关; TYPE =应用程序/ XOP + XML开始=&LT;这里所说信封边界ID&gt;中;启动信息=文/ XML;边界=点击这里云边界ID
                OperationContext.Current.OutgoingMessageProperties [Htt的prequestMessageProperty.Name] = requestMessage;            响应= requestClient.BulkRequestTransmitter(request.ACASecurityHeader,
                                                                    request.Security,楼盘request.ACABusinessHeader,
                                                                    request.ACATransmitterManifestReqDtl,
                                                                    request.ACABulkRequestTransmitter);
            }


  • 修改MIME部分:


  • 9.1。添加新方法:

     公共无效GetHeader(StringBuilder的生成器)
        {
            如果(string.IsNullOrEmpty(内容识别)及&放大器; string.IsNullOrEmpty(ContentType的)及&放大器; string.IsNullOrEmpty(TransferEncoding))
                返回;        如果(!string.IsNullOrEmpty(ContentTypeStart))
            {
                Builder.Append(的String.Format(内容类型:{0},ContentTypeStart));
                Builder.Append(的String.Format(;类型= \\{0} \\,则contentType));
            }
            其他
                Builder.Append(的String.Format(内容类型:{0},则contentType));        如果Builder.Append(string.IsNullOrEmpty(字符集)!)(的String.Format(字符集= {0},字符集));
            Builder.Append(新的char [] {'\\ r','\\ n'});
            Builder.Append(的String.Format(内容传输编码:{0},TransferEncoding));
            Builder.Append(新的char [] {'\\ r','\\ n'});
            Builder.Append(的String.Format(内容ID:{0},内容识别));
            Builder.Append(新的char [] {'\\ r','\\ n'});
            如果(!string.IsNullOrEmpty(ContentDisposition))
                Builder.Append(的String.Format(内容处置:附件;文件名= \\{0} \\,ContentDisposition));
        }

    9.2。添加属性:

     公共字符串ContentDisposition {搞定;组; }

    <醇开始=10>

  • 修改MimeParser SerializeMimeContent()方法:
    更换code的此块:

      Builder.Append(的String.Format(内容类型:{0},item.ContentType));
            如果Builder.Append(string.IsNullOrEmpty(item.CharSet)!)(的String.Format(字符集= {0},item.CharSet));
            Builder.Append(新的char [] {'\\ r','\\ n'});
            Builder.Append(的String.Format(内容传输编码:{0},item.TransferEncoding));
            Builder.Append(新的char [] {'\\ r','\\ n'});
            Builder.Append(的String.Format(内容ID:{0},item.ContentId));


  • 本:

      item.GetHeader(生成器);

    而这应该是它!脱掉你的鞋子和挖蓝调!)))

    I am receiving the following error when attempting to submit through the BulkRequestTransmitter Web Service. The Composition Guide is less than helpful as far as this message goes, and when I compare my SOAP XML with the SOAP from the Composition Guide, they seem to be apples-to-apples. I'm hoping that another set of eyes may be able to see where the problem is.

    The message was not formatted properly and/or cannot be interpreted. Please review the XML standards outlined in Section 3 of the AIR Submission Composition and Reference Guide located at https://www.irs.gov/for-Tax-Pros/Software-Developers/Information-Returns/Affordable-Care-Act-Information-Return-AIR-Program, correct any issues, and try again.

    What I've Tried:

    • Attempted to submit with (and without) whitespace in the SOAP Envelope.
    • Attempted to submit with the Form Data XML in XML format.
    • Attempted to submit with the Form Data in base64string format (as this submission was).
    • Added the ds prefix to the Signature elements. Used this SO post in order to add the prefix to the Signature elements.
    • Added the Form Data in "Pretty Print" format and as according to the updated Composition Guide (v4.2).
    • Copied the formatting of the MIME for the BulkTransmitterService request outlined in section 10.3 of the Composition Guide.
    • Created two solutions: 1.) Manually creating the XML necessary for the SOAP requests and sending via HttpWebRequest object; 2.) Sending a submission request via the WSDL imported to the project as a Service Reference, using custom encoders for GZip and Mtom Encoding and manually creating the XML necessary for the SOAP Status Request (sent via HttpWebRequest).

    Update #1
    Updated the request based on some new additions.

    • Added the ds prefix to the Signature elements.
    • Added the Form Data in "Pretty Print" format and as according to the updated Composition Guide (v4.2: Section 5.4.2).

    Update #2
    I began to manually create the SOAP .xml file within a new instance of Visual Studio importing the schema references as necessary. I'm doing this outside of any sort of application creation.

    In doing so, I was able to find some additional bugs in the SOAP I was creating through my application (thank you for intellisense!). The bugs that I found were within the Manifest XML, as they didn't conform to the IRS schema.

    I will be looking into these in the next 24 hours and update accordingly.

    • The urn:MailingAddressGrp should have a child of either urn:USAddressGrp or urn:ForeignAddressGrp. That child should then contain the proper address elements. My code is currently missing the direct child of the urn:MailingAddressGrp.
    • The value for urn1:DocumentSystemFileNm of Form1094C_Request_[TCC]_yyyyMMddThhmmssfffZ.xml is incorrect. I'm not entirely sure what it should be just yet.
    • The urn1:BulkExchangeFile element, is having an issue related to the xop:Include element I have within. The schema wants a base64Binary type.

    Update #2.5

    • Updated my XML generation process to include the USAddressGrp element.
    • Discovered that I had one extra character in the milliseconds (four instead of three). Once I corrected this, along with removing the string "Form" from the beginning of the file name, the value for the urn1:DocumentSystemFileNm was able to validate against the schema successfully.

    Update #3

    • Updated the Full Request based on the updates I have made. At this point, I am unable to deduce what is wrong with my request. If anyone sees anything glaring, please help!

    Update #4

    • Updated the Full Request based on additional updates made. Removed the ds prefix from the Signature based on another SO user's feedback. This user has gotten these requests to work without having to append the ds prefix to the Signature after the fact and re-compute the signature.

      The SO user also confirmed that his requests are working with an <inc:Include> element being setup as a child element of the <BulkExchangeFile> element.

    • Confirmed the MIME headers are correct as per the sample in section 10.3 of the Composition Guide.

    Update #5

    • I currently have two solutions: one which is sending manually creating the XML necessary for the SOAP requests and sending via HttpWebRequest; and one which is using the WSDL Service Reference for the Submission Request, using the custom encoders outlined below, and manually creating the XML necessary for the SOAP Request of the Status.

      As of this update, Solution 1 gives me the error above when making a Submission Request, and gives me the error below when making the Status Request. However, when using Solution 2, both requests (Submission and Status) give me the error below.

      I am looking into possible certificate issues to see if they make any progress with either of these solutions.

    Update #6

    There were a number of issues I ran into which caused me to be delayed. I'll spare you the nitty-gritty details, however, the short of it is that we did not have the Security Certificate registered with the IRS system, nor did we have the Certificate installed properly so that I could access the information through the X509Store. Finally these things got done, and I was able to test submitting data to the IRS from the server (vs. my localmachine which did not have the proper certificate). Unfortunately, I am still receiving the WS-Security error detailed below. I have updated the Full Request with what I am currently sending.

    An Error Occurred with message: The WS Security Header in the message is invalid. Please review the transmission instructions outlined in Section 5 of the AIR Submission Composition and Reference Guide located at https://www.irs.gov/for-Tax-Pros/Software-Developers/Information-Returns/Affordable-Care-Act-Information-Return-AIR-Program, correct any issues, and try again.


    All line breaks in the MIME headers are as-is, and I believe the line breaks are what is expected. The FormData attachment is being sent as Pretty Print while the SOAP Envelope is not; The SOAP Envelope in this post is formatted for readability.

    UPDATE #7:

    Thanks to users: jstill and fatherOfWine with what they have posted below, and to Bon for earlier assistance on this project. I have broken through one wall in getting the Submission to work. It is now working. The Status request is also working. However, I need to figure out how to process it in order to pull the status and the attachment (error data file) out of it.

    Full Request:

    Content-Encoding: gzip
    Accept-Encoding: gzip, deflate
    Content-Type: multipart/related; type="application/xop+xml"; start="<rootpart>"; start-info="text/xml"; boundary="MIME_boundary"
    SOAPAction: BulkRequestTransmitter
    MIME-Version: 1.0
    Host: la.www4.irs.gov
    
    --MIME_Boundary
    Content-Type: application/xop+xml; charset=UTF-8; type="text/xml"
    Content-Transfer-Encoding: 8bit
    Content-Id: <root_part>
    
    <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
        <s:Header>
            <Security xmlns:h="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                <Signature Id="SIG-E77c57b78ebc54e989bfc9e43604a04a4" xmlns="http://www.w3.org/2000/09/xmldsig#">
                    <SignedInfo>
                        <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#WithComments" />
                        <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
                        <Reference URI="#TS-Eb4799bee41bb4df0a72f52832d283ef7">
                            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                            <DigestValue>[TimestampDigestValue]</DigestValue>
                        </Reference>
                        <Reference URI="#id-E5f1ed32aab8f4578adeee5debd851a62">
                            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                            <DigestValue>[ACABusinessHeaderDigestValue]</DigestValue>
                        </Reference>
                        <Reference URI="#id-E4a71164001994d7f865fc7ddb8055350">
                            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
                            <DigestValue>[ManifestDigestValue]</DigestValue>
                        </Reference>
                    </SignedInfo>
                    <SignatureValue>[SignatureValue]</SignatureValue>
                    <KeyInfo Id="KI-E2309cb142e1a4076a2e71373e6e6b75f">
                        <SecurityTokenReference d6p1:Id="STR-E2751169ee468470290fe5e8bfb34589e" xmlns:d6p1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                            <KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">[KeyIdentifier]</KeyIdentifier>
                        </SecurityTokenReference>
                    </KeyInfo>
                </Signature>
                <a:Timestamp a:Id="TS-Eb4799bee41bb4df0a72f52832d283ef7" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                    <a:Created>2016-05-18T09:51:05.856Z</a:Created>
                    <a:Expires>2016-05-18T10:01:05.856Z</a:Expires>
                </a:Timestamp>
            </Security>
            <ACATransmitterManifestReqDtl a:Id="id-E4a71164001994d7f865fc7ddb8055350" xmlns:h="urn:us:gov:treasury:irs:ext:aca:air:7.0" xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="urn:us:gov:treasury:irs:ext:aca:air:7.0">
                <PaymentYr>2015</PaymentYr>
                <PriorYearDataInd>0</PriorYearDataInd>
                <EIN xmlns="urn:us:gov:treasury:irs:common">000000301</EIN>
                <TransmissionTypeCd>O</TransmissionTypeCd>
                <TestFileCd>T</TestFileCd>
                <OriginalReceiptId />
                <TransmitterNameGrp>
                    <BusinessNameLine1Txt />
                </TransmitterNameGrp>
                <CompanyInformationGrp>
                    <CompanyNm>Selitestthree</CompanyNm>
                    <MailingAddressGrp>
                        <USAddressGrp>
                            <AddressLine1Txt>6689 Willow Court</AddressLine1Txt>
                            <CityNm xmlns="urn:us:gov:treasury:irs:common">Beverly Hills</CityNm>
                            <USStateCd>CA</USStateCd>
                            <USZIPCd xmlns="urn:us:gov:treasury:irs:common">90211</USZIPCd>
                        </USAddressGrp>
                    </MailingAddressGrp>
                    <ContactNameGrp>
                        <PersonFirstNm>Rose</PersonFirstNm>
                        <PersonLastNm>Lincoln</PersonLastNm>
                    </ContactNameGrp>
                    <ContactPhoneNum>5559876543</ContactPhoneNum>
                </CompanyInformationGrp>
                <VendorInformationGrp>
                    <VendorCd>I</VendorCd>
                    <ContactNameGrp>
                        <PersonFirstNm>ContactFirstName</PersonFirstNm>
                        <PersonLastNm>ContactLastName</PersonLastNm>
                    </ContactNameGrp>
                    <ContactPhoneNum>ContactPhoneNumber</ContactPhoneNum>
                </VendorInformationGrp>
                <TotalPayeeRecordCnt>3</TotalPayeeRecordCnt>
                <TotalPayerRecordCnt>1</TotalPayerRecordCnt>
                <SoftwareId>PPACA</SoftwareId>
                <FormTypeCd>1094/1095C</FormTypeCd>
                <BinaryFormatCd xmlns="urn:us:gov:treasury:irs:common">application/xml</BinaryFormatCd>
                <ChecksumAugmentationNum xmlns="urn:us:gov:treasury:irs:common">6b2512ce28f603f76261923d297738e5</ChecksumAugmentationNum>
                <AttachmentByteSizeNum xmlns="urn:us:gov:treasury:irs:common">14076</AttachmentByteSizeNum>
                <DocumentSystemFileNm>1094C_Request_[TCC]_20160518T215105716Z.xml</DocumentSystemFileNm>
            </ACATransmitterManifestReqDtl>
            <ACABusinessHeader a:Id="id-E5f1ed32aab8f4578adeee5debd851a62" xmlns:h="urn:us:gov:treasury:irs:msg:acabusinessheader" xmlns:a="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="urn:us:gov:treasury:irs:msg:acabusinessheader">
                <UniqueTransmissionId xmlns="urn:us:gov:treasury:irs:ext:aca:air:7.0">51958882-c653-4eab-8dfb-287ecc555aaa:SYS12:[TCC]::T</UniqueTransmissionId>
                <Timestamp xmlns="urn:us:gov:treasury:irs:common">2016-05-18T14:51:05.8568594-07:00</Timestamp>
            </ACABusinessHeader>
        </s:Header>
        <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <ACABulkRequestTransmitter xmlns="urn:us:gov:treasury:irs:msg:irsacabulkrequesttransmitter" version="1.0">
                <BulkExchangeFile xmlns="urn:us:gov:treasury:irs:common">
                    <inc:Include href="cid:1094C_Request_BB0S4_20160518T215105716Z.xml" xmlns:inc="http://www.w3.org/2004/08/xop/include" />
                </BulkExchangeFile>
            </ACABulkRequestTransmitter>
        </s:Body>
    </s:Envelope>
    
    --MIME_Boundary
    Content-Type: text/xml; charset=us-ascii
    Content-Transfer-Encoding: 7bit
    Content-Id: <1094C_Request_BB0S4_20160518T215105716Z.xml>
    Content-Disposition: attachment; name="1094C_Request_[TCC]_20160518T215105716Z.xml"
    
    [PrettyPrintFormDataXml]
    --MIME_boundary--
    

    解决方案

    Don't know if it will resolve your issue, but nevertheless i give it a shot. Sometimes help comes from very unexpected sources :)

    1. First of all timestamp fields are in a wrong format: one in businessheader should NOT contain milliseconds at all. I know it for a fact.
    2. In security header timestamp only 3 digits are allowed to represent milliseconds.
    3. Remove empty elements like "OriginalReceiptId" from ACATransmitterManifestReqDtl element: they don't like those.
    4. I hope you are providing them with proper software id, because you have it empty in the payload, but I am sure they would love to have it, imho.:)
    5. And I think the message you've got in the response also have something to do with Signature element. I think they want Signature element to have some prefix("ds" preferably, I guess). But here I am not sure on 100%.

      You see, I am battling same battle as you. And my message security timestamp has prefix "u" and they do not complain about it. Though they didn't like binarysecuritytoken ever.:) I am struggling to generate signature to the IRS liking. WCF is very secretive and does not allow easy prefix changing on soap envelope or allow to choose CanonicalizationMethod algorithm for a signature.

    UPDATE: Been able to successfully send request to the service. Tell you at once: prefixes are unimportant. What was important: CorrectedInd tag must be present in Form1095BUpstreamDetail and attributes recordType="String" lineNum="0" also must be present.

    UPDATE2: Another thing that I've changed I've placed ACABusinessHeader before ManifestDtl. Here are my settings: I am using WCF as carrier and SignedXml to generate signature. Also I am using custom gZip encoder(for obvious reasons0 and custom MtomEncoder to read response from service(yes, yes it's MTOMed:)) can you believe those pokemons?!?!?) and that's not all: they send response as multipart document with only 1 part!:)) I had to adjust my encoder to handle that. And voilà, service started to behave. Hope it might help.

    UPDATE3 First of all make sure data in attachment file correspond to the test scenario you are using as guinea pig. I, probably, sound like a broken record, but that's REALLY important. Now I'll cut the stuff and present what I have. It's a bit crude, but it does the trick.:)

    1.Here is config file portion:
    1.1.Make sure system.serviceModel element contains following portion:

    <extensions>
      <bindingElementExtensions>
        <add name="gzipMessageEncoding" type="<namespaceWhereEncoderLives>.GZipMessageEncodingElement, GZipEncoder, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null" />
      </bindingElementExtensions>
    </extensions>  
    

    1.2. Make sure binding element contains this:

      <customBinding>
        <binding name="BulkRequestTransmitterBinding">
          <gzipMessageEncoding innerMessageEncoding="textMessageEncoding" />
          <httpsTransport />
        </binding>
      </customBinding>
    

    1.3. Change binding of BulkRequestTransmitterPort endpoit under client element to "customBinding"(and change binding name to the name of the custom binding as well) and make sure it contains following portion:

        <identity>
          <dns value="domain from cert" />
        </identity>
    

    Also client element should contain following portion:

      <metadata>
        <policyImporters>
          <extension type="NamespaceToToTheLocationOf.GZipMessageEncodingBindingElementImporter, GZipMessageEncoder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
        </policyImporters>
      </metadata>
    

    1. GZip encoder you could get from following link: https://msdn.microsoft.com/en-us/library/cc138373(v=vs.90).aspx Just download WCF example and dully move whole GZipMessageEncoder project under your project.

    2. Get MTOMEncoder(which I renamed from SwaEncoder for clarity reasons) from this link: Soap-with-Attachments Move following classes into GZipMessageEncoder project:
      MimeContent, MimeParser, MimePart, MTOMEncoder

    3. Modify GZipMessageEncoder class like this:
      4.1. Add following code at the beginning of the class:

         //------------------- MTOM related stuff. Begin. ---------------------
          const string ATTCHMNT_PROP = "attachment_file_content";
          const string ATTCHMNT_CONTENT_ID = "Here goes content id";
      
          private string _ContentType;
          private string _MediaType;
      
          protected MimeContent _MyContent;
          protected MimePart _SoapMimeContent;
          protected MimePart _AttachmentMimeContent;
          protected GZipMessageEncoderFactory _Factory;
          protected MimeParser _MimeParser;
          private void SetupMTOM(GZipMessageEncoderFactory factory)
          {
              //
              _ContentType = "multipart/related";
              _MediaType = _ContentType;
      
              //
              // Create owned objects
              //
              _Factory = factory;
              _MimeParser = new MimeParser();
      
              //
              // Create object for the mime content message
              // 
              _SoapMimeContent = new MimePart()
              {
                  ContentTypeStart = "application/xop+xml",
                  ContentType = "text/xml",
                  ContentId = "Here goes envelope MIME id from HTTP Content-Type header",   // TODO: make content id dynamic or configurable?
                  CharSet = "UTF-8",                                  // TODO: make charset configurable?
                  TransferEncoding = "8bit"                         // TODO: make transfer-encoding configurable?
              };
              _AttachmentMimeContent = new MimePart()
              {
                  ContentType = "application/xml",                    // TODO: AttachmentMimeContent.ContentType configurable?
                  ContentId = ATTCHMNT_CONTENT_ID,                    // TODO: AttachmentMimeContent.ContentId configurable/dynamic?
                  TransferEncoding = "7bit"                         // TODO: AttachmentMimeContent.TransferEncoding dynamic/configurable?
              };
              _MyContent = new MimeContent()
              {
                  Boundary = "here goes boundary id"  // TODO: MimeContent.Boundary configurable/dynamic?
             };
              _MyContent.Parts.Add(_SoapMimeContent);
              _MyContent.Parts.Add(_AttachmentMimeContent);
              _MyContent.SetAsStartPart(_SoapMimeContent);
          }
          //------------------- MTOM related stuff. End. ----------------------
      

    4.2. Modify Method WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) like this:

    public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
            {
                ArraySegment<byte> buffer = innerEncoder.WriteMessage(message, maxMessageSize, bufferManager, 0);
                var requestSOAPEnvelopeXml = System.Text.Encoding.UTF8.GetString(buffer.Array);
    
                //Here you create Security node and sign the request. For ex:
                requestSOAPEnvelopeXml = SigngEnvelope(requestSOAPEnvelopeXml);
                //Here you are getting 1094\1095 forms xml payload.
                string fileContent = GetAttachmentFileContent();
    
                //Here comes the MTOMing...
                _SoapMimeContent.Content = System.Text.Encoding.UTF8.GetBytes(requestSOAPEnvelopeXml);
                _AttachmentMimeContent.Content = System.Text.Encoding.UTF8.GetBytes(fileContent);
    
                _MyContent.Parts.Where(m=> m.ContentId!=null && m.ContentId.Equals(ATTCHMNT_CONTENT_ID)).Single().ContentDisposition = GetFileName(envelope);
                // Now create the message content for the stream
                byte[] MimeContentBytes = _MimeParser.SerializeMimeContent(_MyContent);
                int MimeContentLength = MimeContentBytes.Length;
    
                // Write the mime content into the section of the buffer passed into the method
                byte[] TargetBuffer = bufferManager.TakeBuffer(MimeContentLength + messageOffset);
                Array.Copy(MimeContentBytes, 0, TargetBuffer, messageOffset, MimeContentLength);
    
                // Return the segment of the buffer to the framework
                return CompressBuffer(new ArraySegment<byte>(TargetBuffer, messageOffset, MimeContentLength), bufferManager, messageOffset);                
            }
    

    4.3. Override couple more methods like this:

    public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
            {
                ArraySegment<byte> decompressedBuffer = DecompressBuffer(buffer, bufferManager);
    
                MtomEncoder mtomEncoder = new MtomEncoder(innerEncoder, _Factory);
                Message returnMessage = mtomEncoder.ReadMessage(buffer, bufferManager, contentType);
                returnMessage.Properties.Encoder = mtomEncoder;
    
                return returnMessage;
            }
    
            public override bool IsContentTypeSupported(string contentType)
            {
                return true;
            }
    

    4.4. Make sure GZipMessage constructor looks like this:

            internal GZipMessageEncoder(MessageEncoder messageEncoder, GZipMessageEncoderFactory factory)
                : base()
            {
                if (messageEncoder == null)
                    throw new ArgumentNullException("messageEncoder", "A valid message encoder must be passed to the GZipEncoder");
                innerEncoder = messageEncoder;
    
                SetupMTOM(factory);
            }
    

    5. Make sure GZipMessageEncodingBindingElement class has following method:

        public override void ApplyConfiguration(BindingElement bindingElement)
        {
            GZipMessageEncodingBindingElement binding = (GZipMessageEncodingBindingElement)bindingElement;
            PropertyInformationCollection propertyInfo = this.ElementInformation.Properties;
            if (propertyInfo["innerMessageEncoding"].ValueOrigin != PropertyValueOrigin.Default)
            {
                switch (this.InnerMessageEncoding)
                {
                    case "textMessageEncoding":
                        binding.InnerMessageEncodingBindingElement = 
                            new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8);
                        break;
                    case "binaryMessageEncoding":
                        binding.InnerMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();
                        break;
                }
            }
        }
    

    1. Modify MTOMEncoder class. Make sure that following method looks like this:

      public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders, string contentType)
      {
          VerifyOperationContext();
      
          if (contentType.ToLower().StartsWith("multipart/related"))
          {
              byte[] ContentBytes = new byte[stream.Length];
              stream.Read(ContentBytes, 0, ContentBytes.Length);
              MimeContent Content = _MimeParser.DeserializeMimeContent(contentType, ContentBytes);
      
              if (Content.Parts.Count >= 1)
              {
                  MemoryStream ms = new MemoryStream(Content.Parts[0].Content);
                  //At least for now IRS is sending SOAP envelope as 1st part(and only part(sic!) of MULTIpart response) as xml. 
                  Message Msg = ReadMessage(ms, int.MaxValue, "text/xml");//Content.Parts[0].ContentType);
      
                  if( Content.Parts.Count>1 )
                      Msg.Properties.Add(ATTCHMNT_PROP, Content.Parts[1].Content);
      
                  return Msg;
              }
              else
              {
                  throw new ApplicationException("Invalid mime message sent! Soap with attachments makes sense, only, with at least 2 mime message content parts!");
              }
          }
          else if (contentType.ToLower().StartsWith("text/xml"))
          {
              XmlReader Reader = XmlReader.Create(stream);
              return Message.CreateMessage(Reader, maxSizeOfHeaders, MessageVersion);
          }
          else
          {
              throw new ApplicationException(
                  string.Format(
                      "Invalid content type for reading message: {0}! Supported content types are multipart/related and text/xml!",
                      contentType));
          }
      }
      

    2. GZipMessageEncoderFactory class constructor should look like this:

         public GZipMessageEncoderFactory(MessageEncoderFactory messageEncoderFactory)
      {
          if (messageEncoderFactory == null)
              throw new ArgumentNullException("messageEncoderFactory", "A valid message encoder factory must be passed to the GZipEncoder");
          encoder = new GZipMessageEncoder(messageEncoderFactory.Encoder, this);
      }
      

    3. This is how I call the service:

         var requestClient = new BulkRequestTransmitterPortTypeClient("BulkRequestTransmitterPort");
      
              requestClient.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.None;
       #if DEBUG
              var vs = requestClient.Endpoint.Behaviors.Where((i) => i.GetType().Namespace.Contains("VisualStudio"));
              if( vs!=null )
               requestClient.Endpoint.Behaviors.Remove((System.ServiceModel.Description.IEndpointBehavior)vs.Single());
      #endif                
         using (var scope = new OperationContextScope(requestClient.InnerChannel))
              {
                   //Adding proper HTTP Header to an outgoing requqest.
                  HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
      
                  requestMessage.Headers["Content-Encoding"] = "gzip";
                  requestMessage.Headers["Content-Type"] = @"multipart/related; type=""application/xop+xml"";start=""<Here goes envelope boundary id>"";start-info=""text/xml"";boundary=""here goes boundary id""";
                  OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
      
                  response = requestClient.BulkRequestTransmitter(request.ACASecurityHeader,
                                                                      request.Security, ref request.ACABusinessHeader,
                                                                      request.ACATransmitterManifestReqDtl, 
                                                                      request.ACABulkRequestTransmitter);
              }
      

    4. Modify Mime Part:

    9.1. Add new method:

        public void GetHeader(StringBuilder Builder)
        {
            if (string.IsNullOrEmpty(ContentId) && string.IsNullOrEmpty(ContentType) && string.IsNullOrEmpty(TransferEncoding))
                return;
    
            if (!string.IsNullOrEmpty(ContentTypeStart))
            {
                Builder.Append(string.Format("Content-Type: {0}", ContentTypeStart));
                Builder.Append(string.Format("; type=\"{0}\"", ContentType));
            }
            else
                Builder.Append(string.Format("Content-Type: {0}", ContentType));
    
            if (!string.IsNullOrEmpty(CharSet)) Builder.Append(string.Format("; charset={0}", CharSet));
            Builder.Append(new char[] { '\r', '\n' });
            Builder.Append(string.Format("Content-Transfer-Encoding: {0}", TransferEncoding));
            Builder.Append(new char[] { '\r', '\n' });
            Builder.Append(string.Format("Content-Id: {0}", ContentId));
            Builder.Append(new char[] { '\r', '\n' });
            if (!string.IsNullOrEmpty(ContentDisposition))
                Builder.Append(string.Format("Content-Disposition: attachment; filename=\"{0}\"", ContentDisposition));
        }
    

    9.2. Add property:

       public string ContentDisposition { get; set; }
    

    1. Modify MimeParser SerializeMimeContent() method: replace this block of code:

             Builder.Append(string.Format("Content-Type: {0}", item.ContentType));
              if (!string.IsNullOrEmpty(item.CharSet)) Builder.Append(string.Format("; charset={0}", item.CharSet));
              Builder.Append(new char[] { '\r', '\n' });
              Builder.Append(string.Format("Content-Transfer-Encoding: {0}", item.TransferEncoding));
              Builder.Append(new char[] { '\r', '\n' });
              Builder.Append(string.Format("Content-Id: {0}", item.ContentId));
      

    with this:

    item.GetHeader(Builder);
    

    And that's should be it! Kick off your shoes and dig the blues!:)))

    这篇关于IRS-A2A BulkRequestTransmitter消息无法正常formmatted和/或不能PTED间$ P $的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆