WCF - how to create programatically custom binding with binary encoding over HTTP(S)

后端 未结 3 801
有刺的猬
有刺的猬 2021-02-09 19:53

I\'d like to convert my current HTTP/HTTPS WCF binding settings to use binary message encoding and I need to do it in code - not in XML configuration. AFAIK it\'s necessary to

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 20:32

    I almost forgot this question, but here is my custom binding class which works with binary binding over HTTP with username+password validation and also allows to turn GZip compression on...

        public class CustomHttpBinding: CustomBinding
    {
        private readonly bool useHttps;
        private readonly bool useBinaryEncoding;
        private readonly bool useCompression;
        private readonly HttpTransportBindingElement transport;
    
        public CustomHttpBinding(bool useHttps, bool binaryEncoding = true, bool compressMessages = false)
        {
            this.useHttps = useHttps;
            transport = useHttps ? new HttpsTransportBindingElement() : new HttpTransportBindingElement();
            useBinaryEncoding = binaryEncoding;
            useCompression = compressMessages;
        }
    
        public long MaxMessageSize{set
        {
            transport.MaxReceivedMessageSize = value;
            transport.MaxBufferSize = (int) value;
        }}
    
        public override BindingElementCollection CreateBindingElements()
        {
            BindingElement security;
            if (useHttps)
            {
                security = SecurityBindingElement.CreateSecureConversationBindingElement(
                    SecurityBindingElement.CreateUserNameOverTransportBindingElement());
            }
            else
            {
                security = SecurityBindingElement.CreateSecureConversationBindingElement(
                    SecurityBindingElement.CreateUserNameForSslBindingElement(true));
            }
    
            MessageEncodingBindingElement encoding;
            if (useCompression)
            {
                encoding = new GZipMessageEncodingBindingElement(useBinaryEncoding
                                                                    ? (MessageEncodingBindingElement)
                                                                      new BinaryMessageEncodingBindingElement()
                                                                    : new TextMessageEncodingBindingElement());
            }
            else
            {
                encoding = useBinaryEncoding
                            ? (MessageEncodingBindingElement) new BinaryMessageEncodingBindingElement()
                            : new TextMessageEncodingBindingElement();
            }
    
            return new BindingElementCollection(new[]
                {
                    security,
                    encoding,
                    transport,
                });
        }
    }
    

提交回复
热议问题