以编程方式创建自定义绑定

时间:2012-03-02 13:56:36

标签: .net wcf binding web-config app-config

我们需要在WCF Web服务中进行压缩,并且已经找到了一个很好的解决方案:

http://www.codeproject.com/Articles/53718/Extending-WCF-Part-II

只有一个问题。配置文件是没有选项。如何在代码中创建自定义绑定?

  <customBinding>
    <binding name="ZipBinding" closeTimeout="00:10:00" 
openTimeout="00:10:00" receiveTimeout="00:10:00" 
    sendTimeout="00:10:00">
      <customMessageEncoding innerMessageEncoding="mtomMessageEncoding" 
    messageEncoderType="YourAssemblyName.YourMessageEncoder, 
    WcfExtensions">
        <readerQuotas maxDepth="999999999" 
            maxStringContentLength="999999999" 
    maxArrayLength="999999999" maxBytesPerRead="999999999" 
    maxNameTableCharCount="999999999">
        </readerQuotas>
      </customMessageEncoding>
      <httpTransport maxBufferSize="999999999" 
        maxReceivedMessageSize="999999999" 
    authenticationScheme="Anonymous" 
    proxyAuthenticationScheme="Anonymous" useDefaultWebProxy="true"/>
    </binding>
  </customBinding>

这就是我的想法:

MessageEncodingBindingElementExtension customMessageEncoding = new MessageEncodingBindingElementExtension
{
    InnerMessageEncoding = "binaryMessageEncoding",
    MessageEncoderType = "WcfExtensions.GZipMessageEncoder, WcfExtensions",
};
customMessageEncoding.ReaderQuotas.MaxDepth = 999999999;
customMessageEncoding.ReaderQuotas.MaxStringContentLength = 999999999;
customMessageEncoding.ReaderQuotas.MaxArrayLength = 999999999;
customMessageEncoding.ReaderQuotas.MaxBytesPerRead = 999999999;
customMessageEncoding.ReaderQuotas.MaxNameTableCharCount = 999999999;

CustomBinding zipBinding = new CustomBinding(customMessageEncoding, new HttpTransportBindingElement
{
    MaxBufferSize = 999999999,
    MaxReceivedMessageSize = 999999999,
    AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous,
    ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous,
    UseDefaultWebProxy = true
});

zipBinding.CloseTimeout = new TimeSpan(0, 10, 0);
zipBinding.OpenTimeout = new TimeSpan(0, 10, 0);
zipBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
zipBinding.SendTimeout = new TimeSpan(0, 10, 0);

但由于某种原因,CustomBinding不接受customMessageEncoding ...

1 个答案:

答案 0 :(得分:3)

类型CustomBinding的构造函数中的第一个参数只接受BindingElement子类。您指定的类是BindingElementExtensionElement子类(用于自定义配置Xml)。

不应该将BindingElementExtensionElement的子类传递给CustomBinding构造函数,而应该创建一个BindingElement的合适子类实例(例如BinaryMessageEncodingBindingElement)并调用{ {1}} BindingElementExtensionElement方法,传入ApplyConfiguration

然后将BindingElement的实例传递给BindingElement构造函数。

CustomBinding