C# 如何手动创建web引用

C# 如何手动创建web引用,c#,visual-studio-2010,soap,soap-client,C#,Visual Studio 2010,Soap,Soap Client,我知道我可以通过使用VisualStudio添加web引用来指向一些SOAP web服务 但我需要从代码开始 如何在代码中手动创建web引用对象并从该对象访问所有方法? 基本上,我希望避免生成代理类。如果您可以获得服务合同(接口)的副本(可以对此提供帮助),那么您可以将其包含在项目中,并使用ChannelFactory类动态创建一个通道,供客户机与服务通信 我倾向于将其封装在SAL(服务应用层)中,以便根据需要重用 这是一个简单(绝对不完整!)的示例,演示了如何连接到虚构的时间服务并调用GetT

我知道我可以通过使用VisualStudio添加web引用来指向一些SOAP web服务

但我需要从代码开始

如何在代码中手动创建web引用对象并从该对象访问所有方法?

基本上,我希望避免生成代理类。

如果您可以获得服务合同(接口)的副本(可以对此提供帮助),那么您可以将其包含在项目中,并使用ChannelFactory类动态创建一个通道,供客户机与服务通信

我倾向于将其封装在SAL(服务应用层)中,以便根据需要重用

这是一个简单(绝对不完整!)的示例,演示了如何连接到虚构的时间服务并调用GetTime()操作,而无需使用VS生成的代理:

public class TimeSAL : IDisposable
{
    private ChannelFactory<ITimeService> timeServiceProxyFactory;
    private ITimeService timeServiceProxy;

    private ITimeService TimeService
    {
        get
        {
            //create channel factory if not there
            if (timeServiceProxyFactory == null)
                timeServiceProxyFactory = new ChannelFactory<ITimeService>(new BasicHttpBinding(), new EndpointAddress("http://url_to_my_timeservice_endpoint"));  //

            if (timeServiceProxy == null)
                timeServiceProxy = amlProxyFactory.CreateChannel();

            return timeServiceProxy;
        }

    }

    public string GetTime()
    {
        return TimeService.GetTime();
    }

    public void Dispose()
    {
        //dispose of ChannelFactory and proxy.
        //ensure you check for comm faults to abort before closing
    }

}
如果您无法获得服务合同的副本,那么一个冗长的方法就是手工编写soap请求。Fiddler或soapUI可以帮助实现消息的外观


希望这能有所帮助。

“基本上我希望避免生成代理类”-为什么?我只能从特定的IP地址访问服务URL。这就是生产服务器地址。我需要在本地机器上生成它,但不能。
 ....
 using(TimeSAL timeSAL = new TimeSAL())
 {
   myBusinessObject.CurrentTime = timeSAL.GetTime();
 }
 ....