温馨提示×

C#动态调用WSDL服务怎么做

c#
小樊
88
2024-06-24 11:30:33
栏目: 编程语言

在C#中动态调用WSDL服务可以使用ServiceModel.ClientBase类来实现。以下是一个示例代码:

using System;
using System.ServiceModel;

namespace DynamicWSDLClient
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建动态绑定
            BasicHttpBinding binding = new BasicHttpBinding();
            EndpointAddress endpointAddress = new EndpointAddress("http://www.example.com/Service.svc");

            // 创建ChannelFactory
            ChannelFactory<IService> factory = new ChannelFactory<IService>(binding, endpointAddress);
            IService client = factory.CreateChannel();

            // 调用服务方法
            string result = client.MyServiceMethod();

            Console.WriteLine(result);
        }
    }

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        string MyServiceMethod();
    }
}

在上面的示例中,首先创建了一个动态绑定,并指定了WSDL服务的地址。然后创建了一个ChannelFactory对象,并传入绑定和服务地址。最后通过CreateChannel方法创建了一个实现了IService接口的代理对象,通过该对象可以调用WSDL服务中定义的方法。

0