Skip to main content
 首页 » 编程设计

c#之SOAP Web 服务和 C#

2024年01月25日27lori

我需要在 C# 中监听来自 Web 服务的请求并在 C# 中响应这些请求。这是什么方法?

请您参考如下方法:

我假设您已经有了想要使用的 Web 服务。有几个关于在 Web 上使用 Web 服务的示例(例如:Consuming web services from a WinForms app)。

添加网络引用

首先,您需要向您的 C# 项目添加一个网络引用。在 VS2005 中,您可以通过右键单击项目并选择“添加 Web 引用”并提供 Web 服务的 URL 来完成此操作。在 VS2008 或更新版本中,有几次额外的点击,如 described here。 .

完成后,VS 会为您生成所有必需的代理类,同时提供同步和异步调用的方法,您可以像在本地实例化对象一样使用它们。

查看生成的类

例如,如果您的 Web 服务只有一个方法 (DoSomething),并且位于 www.example.com/MyService.asmx(也名为“MyService"), Visual Studio 将创建一个名为“MyService”的类,它看起来像这样:

namespace MyNamespace // <-- this is the name you choose when you  
{                     //     added the web reference 
 
    public class MyService : SoapHttpClientProtocol 
    { 
         // synchronous execution 
         public void DoSomething() 
         { 
 
         } 
 
         // async execution 
         public void DoSomethingAsync() 
         { 
 
         } 
 
         // callback event for async execution 
         public event DoSomethingCompletedEventHandler DoSomethingCompleted; 
     } 
} 

要检查生成的命名空间的内容,请在解决方案资源管理器中双击您的 Web 引用(它应该位于名为“Web References”的文件夹中)。这将打开对象浏览器。

同步使用生成的类

使用您的类最简单的方法是创建一个实例,然后调用该方法:

// create a new instance of the service 
MyService service = new MyService(); 
 
// invoke the method 
service.DoSomething(); // <-- this will block the thread until completed 

异步使用生成的类

要使用异步版本,您可以附加一个事件处理程序:

// create a new instance of the service 
MyService service = new MyService(); 
 
// attach the event handler 
service.DoSomethingCompleted += MyEventHandler; 
 
// invoke the method asynchronously 
service.DoSomethingAsync(); // <-- this will be invoked on a background thread