简体   繁体   中英

Manually add binding at run-time

For reasons that pertain to my specific situation, I'm trying to remove as much as possible from a App.Config file. One of the items in there that I'm trying to move into code is information pertaining to a web service. I've taken the information from the App.Config and created a BasicHttpBinding class :

System.ServiceModel.BasicHttpBinding dss = new System.ServiceModel.BasicHttpBinding();
        dss.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.None;
        dss.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.None;
        dss.Security.Transport.ProxyCredentialType = System.ServiceModel.HttpProxyCredentialType.None;
        dss.Security.Transport.Realm = "";

        dss.Security.Message.ClientCredentialType = System.ServiceModel.BasicHttpMessageCredentialType.UserName;

        dss.Name = "DataServiceSoap";
        dss.CloseTimeout = System.TimeSpan.Parse("00:01:00");
        dss.OpenTimeout = System.TimeSpan.Parse("00:01:00");
        dss.ReceiveTimeout = System.TimeSpan.Parse("00:10:00");
        dss.SendTimeout = System.TimeSpan.Parse("00:10:00");
        dss.AllowCookies = false;
        dss.BypassProxyOnLocal = false;
        dss.HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard;
        dss.MaxBufferSize = 655360;
        dss.MaxBufferPoolSize = 524288;
        dss.MaxReceivedMessageSize = 655360;
        dss.MessageEncoding = System.ServiceModel.WSMessageEncoding.Text;
        dss.TextEncoding = new System.Text.UTF8Encoding();
        dss.TransferMode = System.ServiceModel.TransferMode.Buffered;
        dss.UseDefaultWebProxy = true;
        dss.ReaderQuotas.MaxDepth = 32;
        dss.ReaderQuotas.MaxStringContentLength = 8192;
        dss.ReaderQuotas.MaxArrayLength = 16384;
        dss.ReaderQuotas.MaxBytesPerRead = 4096;
        dss.ReaderQuotas.MaxNameTableCharCount = 16384;

After that, I created a Uri to point to the address of the web service:

Uri baseAddress = new Uri("http://localservice/dataservice.asmx");

How do I eventually add the client endpoint address and binding? Do I have to open up channels or is there an easier class to implement that takes care of this?

Here is an easy way to do that programmatically using a ChannelFactory.

        BasicHttpBinding binding = new BasicHttpBinding();
        EndpointAddress address = new EndpointAddress("Your uri here");

        ChannelFactory<IContract> factory = new ChannelFactory<IContract>(binding, address);
        IContract channel = factory.CreateChannel();
        channel.YourMethod();
        ((ICommunicationObject)channel).Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM