如何在运行时设置端点
我有基于本教程的应用程序
我用来测试与服务器的连接的方法(在客户端应用程序中):
public class PBMBService : IService { private void btnPing_Click(object sender, EventArgs e) { ServiceClient service = new ServiceClient(); tbInfo.Text = service.Ping().Replace("\n", "\r\n"); service.Close(); } //other methods }
服务主要function:
class Program { static void Main(string[] args) { Uri baseAddress = new Uri("http://localhost:8000/PBMB"); ServiceHost selfHost = new ServiceHost(typeof(PBMBService), baseAddress); try { selfHost.AddServiceEndpoint( typeof(IService), new WSHttpBinding(), "PBMBService"); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; selfHost.Description.Behaviors.Add(smb); selfHost.Open(); Console.WriteLine("Serwis gotowy."); Console.WriteLine("Naciśnij aby zamknąć serwis."); Console.WriteLine(); Console.ReadLine(); selfHost.Close(); } catch (CommunicationException ce) { Console.WriteLine("Nastąpił wyjątek: {0}", ce.Message); selfHost.Abort(); } } }
在app.config
我有:
我可以从这里更改IP。 但是如何在运行时更改它(即从文件读取地址/ IP)?
您可以在创建客户端类后替换服务端点:
public class PBMBService : IService { private void btnPing_Click(object sender, EventArgs e) { ServiceClient service = new ServiceClient(); service.Endpoint.Address = new EndpointAddress("http://the.new.address/to/the/service"); tbInfo.Text = service.Ping().Replace("\n", "\r\n"); service.Close(); } }
您可以使用以下渠道工厂:
using System.ServiceModel; namespace PgAuthentication { public class ServiceClientFactory : ChannelFactory where TChannel : class { public TChannel Create(string url) { return CreateChannel(new BasicHttpBinding { Security = { Mode = BasicHttpSecurityMode.None } }, new EndpointAddress(url)); } } }
您可以使用以下代码:
Console.WriteLine( new ServiceClientFactory() .Create("http://crm.payamgostar.com/Services/IAuthentication.svc") .AuthenticateUserNameAndPassWord("o", "123", "o", "123").Success);