SOAP Web service and C#

本文关键字:and service Web SOAP | 更新日期: 2023-09-27 17:53:18

我需要在c#中监听来自web服务的请求,并在c#中响应它们。怎么做呢?

SOAP Web service and C#

我假设您已经有了希望使用的web服务。这里有几个关于在web上消费web服务的例子(例如:从WinForms应用程序中消费web服务)。

添加web引用

首先,你需要添加一个web引用到你的c#项目。在VS2005中,您可以通过右键单击项目并选择"添加web引用",并提供web服务的url来实现这一点。在VS2008或更新版本中,有几个额外的点击,如下所述。

在你完成这些之后,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"的文件夹中)。这将打开Object浏览器。

同步使用生成的类

使用类的最简单方法是创建一个实例,并调用方法:

// 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

我建议先看看这个。

如果你的问题是:Web服务一定要用c#写吗?答案是"不"。您可以用多种语言编写Web服务,包括Java、VB。.NET甚至是COBOL.NET。

如果你的问题是:Web服务是否必须用与使用它们的程序相同的语言编写,答案再次是"不",只要你的Web服务不与客户端在同一个Visual Studio项目中。

在解决方案资源管理器中选择"Add Service Reference"(右键单击你的项目),然后将你想要使用的WebService的URL添加到地址栏,然后点击"Go"。

客户端应该从Visual Studio自动创建