簡體   English   中英

如何在運行時設置端點

[英]How to set endpoint in runtime

我有基於本教程的應用程序

我用來測試與服務器的連接的方法(在客戶端應用程序中):

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)?

您可以在創建客戶端類后替換服務端點:

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<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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM