Create WCF endpoint configurations in the client app, in code?

后端 未结 2 887
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 15:40

I am trying to consume a WCF web service from a .NET client application, and I think I need to be able to programmatically create endpoints, but I don\'t know how. I think I

相关标签:
2条回答
  • 2020-12-05 15:50

    An east way to consume a WCF service if you have a reference to the assembly which defines the interface, is using the System.ServiceModel.ChannelFactory class.

    For example, if you would like to use BasicHttpBinding:

    var emailService = ChannelFactory<IEmailService>.CreateChannel(new BasicHttpBinding(), new EndpointAddress(new Uri("http://some-uri-here.com/));
    

    If you don't have a reference to the service assembly, then you can use one of the overloaded constructors on the generated proxy class to specify binding settings.

    0 讨论(0)
  • 2020-12-05 15:52

    By default, when you do an Add Service Reference operation, the WCF runtime will generate the client-side proxy for you.

    The simplest way to use it is to instantiate the client proxy with a constructor that takes no parameters, and just grab the info from the app.config:

    YourServiceClient proxy = new YourServiceClient();
    

    This requires the config file to have a <client> entry with your service contract - if not, you'll get the error you have.

    But the client side proxy class generated by the WCF runtime also has additional constructors - one takes an endpoint address and a binding, for instance:

    BasicHttpBinding binding = new BasicHttpBinding(SecurityMode.None);
    EndpointAddress epa = new EndpointAddress("http://localhost:8282/basic");
    
    YourServiceClient proxy = new YourServiceClient(binding, epa);
    

    With this setup, no config file at all is needed - you're defining everything in code. Of course, you can also set just about any other properties of your binding and/or endpoint here in code.

    0 讨论(0)
提交回复
热议问题