简体   繁体   中英

Consume WCF service in winform, how to dynamically set Endpoint element and contract

I have build a test WCF Service Service1.svc I have added service reference of the service to my Winform. Its working good and i can easily consume the WCF service in winform. But i got a major problem :

  1. When i rename or delete the 'MyProject.exe.config' file. It is showing error ' Could not find endpoint element with name BasicHttpBinding_IService1 and contract ServiceReferenct1.IService1

    Since 'MyProject.exe.config' file contains binding and endpoint address which i don't want to share with client or anyone.

    Is there any way to dynamically set endpoint element and contract without using 'MyProject.exe.config' file ? 在此处输入图片说明

App.config :

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" />
            </basicHttpBinding>
        </bindings>

        <client>
            <endpoint  address="http://svc.phed.net/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
                name="BasicHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>
  1. How can i change the Default Message shown by service:

    You have created a service. To test this service, you will need to create a client and use it to call the service. You can do this using the svcutil.exe tool from the command line with the following syntax:

If you don't have the service configuration, you can create a proxy manually.

Here is an example:

var binding = new BasicHttpBinding();
                var endpoint = new EndpointAddress("YourEndPoint");
                var channelFactory = new ChannelFactory<YourInterface>(binding, endpoint);

                YourInterface client = null;
                client = channelFactory.CreateChannel();
                client.YourOperation();

In above example, I've used the BasicHttpBinding. If you're using another binding, just use the right class, for instance a NetTcpBinding.

If you handle your service in a try/catch block you can be able to handle this error and throw a most friendly message to your client.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM