如何在运行时设置端点

Ich*_*ann 5 c# wcf visual-studio-2010

我有基于本教程的应用程序

我用来测试与服务器的连接的方法(在客户端应用程序中):

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
}
Run Code Online (Sandbox Code Playgroud)

服务主要功能:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我可以从这里更改IP.但是如何在运行时更改它(即从文件读取地址/ IP)?

car*_*ira 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();
    }
}
Run Code Online (Sandbox Code Playgroud)