我的申请基于this tutorial
我用来测试与服务器的连接的方法(在客户端应用程序中):
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
}
服务主要功能:
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 <ENTER> 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
我有:
<client>
<endpoint address="http://localhost:8000/PBMB/PBMBService" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService" contract="IService"
name="WSHttpBinding_IService">
<identity>
<userPrincipalName value="PPC\Pawel" />
</identity>
</endpoint>
</client>
我可以从这里更改IP。但是如何在运行时更改它(即从文件读取地址/ IP)?
答案 0 :(得分:15)
您可以在创建客户端类后替换服务端点:
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();
}
}
答案 1 :(得分:0)
您可以使用以下渠道工厂:
using System.ServiceModel;
namespace PgAuthentication
{
public class ServiceClientFactory<TChannel> : ChannelFactory<TChannel> where TChannel : class
{
public TChannel Create(string url)
{
return CreateChannel(new BasicHttpBinding { Security = { Mode = BasicHttpSecurityMode.None } }, new EndpointAddress(url));
}
}
}
您可以使用以下代码:
Console.WriteLine(
new ServiceClientFactory<IAuthenticationChannel>()
.Create("http://crm.payamgostar.com/Services/IAuthentication.svc")
.AuthenticateUserNameAndPassWord("o", "123", "o", "123").Success);