在运行时手动添加绑定

本文关键字:添加 绑定 运行时 | 更新日期: 2023-09-27 17:48:57

由于与我的具体情况有关的原因,我试图从App.Config文件中尽可能多地删除。其中一项我想要转化为代码的是与web服务相关的信息。我从App.Config中获取了信息,并创建了一个BasicHttpBinding类:

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;

之后,我创建了一个指向web服务地址的Uri:

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

我最终如何添加客户端端点地址和绑定?我是否必须打开通道,或者是否有更容易实现的类来处理这个问题?

在运行时手动添加绑定

这里有一种简单的方法可以通过编程方式使用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();