[ASP.NET] WCF 傳輸超過 65536 的資料

  • 7441
  • 0
  • 2016-09-19

WCF 傳輸超過 65536 的資料

如果要透過 WCF 傳輸巨量資料時,可以透過在 Web.Config 加上一些參數來完成,

最近剛好有碰到此類需求,要透過 WCF 提供大量資料給外單位使用,

此篇紀錄一下要注意的地方。

以下的標籤都是放在 <system.serviceModel> 裡面

我們首先在 <bindings> 的標籤底下建立一個 basicHttpBinding,並加上底下的屬性和標籤

maxReceivedMessageSize = "2147483647"

<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" maxDepth="32 />

<bindings>      
  <basicHttpBinding>       
    <binding name="BasicHttpBinding_BigData" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />          
      </security>
      <readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" maxDepth="32" />
    </binding>
  </basicHttpBinding>
</bindings>

maxBufferSize 不用指定沒關係,只要修改 maxReceivedMessageSize 即可。

security 是設定驗證的方式,因公司使用 Windows AD,所以我設定 Windows 驗證。

接著在 <behaviros> <serviceBehaviors>下建立一個 behavior

並在裡面加上 <dataContractSerializer maxItemsInObjectGraph="2147483647" />

<behaviors>
  <serviceBehaviors>
    <behavior name="Behavior">
      <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" />
      <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="true" />
      <dataContractSerializer maxItemsInObjectGraph="2147483647" />
    </behavior>
  </serviceBehaviors>
</behaviors>

然後在你要提供的 WCF 就可以使用這兩組設定,在 <services> 底下新建一個你要提供出去的 service

並在 <service> 裡使用 behaviorConfiguration 的屬性,

以及在 <endpoint> 裡使用 bindingConfiguration 的屬性,

名稱就是上面 bindingbehavior 的 name

<services>
  <service behaviorConfiguration="Behavior" name="HRInfo.Wcf.EmployeeService">
    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_BigData"
      name="BasicHttpBinding_BigData" contract="HRInfo.Wcf.IEmployeeService" />
  </service>
</services>

以上都弄好後就可以先用 WcfTestClient 執行測試,

測試時可能會發生不管你怎麼修改專案的 Web.Config,

測試服務時都還是會跳出要修改 maxReceivedMessageSize 的 Exception,

這是因為 WcfTestClient 有自己的 Web.Config,而且這個 Web.config 不會吃到前面加的那些設定,

所以我們要啟動後再去手動修改裡面的參數值才行。

對組態檔點右鍵,使用 SvcConfigEditor 編輯

可以看到 MaxReceivedMessageSize 還是 65536,因此我們要修改剛剛上面提到的相關屬性的設定

修改完後再執行應該就沒問題了。

Release 出去後,要注意 Client 端在使用時,Web.Config 的繫結端點(binding)也要加上 maxReceivedMessageSize = "2147483647"