打印本文 打印本文 关闭窗口 关闭窗口
ASP.NET Web Service如何工作(2)
作者:武汉SEO闵涛  文章来源:敏韬网  点击数2247  更新时间:2009/4/23 10:50:41  文章录入:mintao  责任编辑:mintao

HTTP管道一旦调用了.asmx句柄,便开始了XML、XSD、SOAP和WSDL的处理。.asmx句柄提供的余下的功能被分为三个领域:

消息分派

当.asmx句柄被HTTP管道调用时,通过查看.asmx文件中的WebService声明,确定检查哪个.NET类。然后它观察到来的HTTP消息中的信息,确定调用引用类中的哪个方法。为了调用前面例子中的Add方法,HTTP请求消息应像下面一样:

POST /math/math.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/Add"
 
<soap:Envelope 
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
>
  <soap:Body>
    <Add xmlns="http://tempuri.org/">
      <x>33</x>
      <y>66</y>
    </Add>
  </soap:Body>
</soap:Envelope>

上面的HTTP请求消息中有两条信息可以用来确定调用类中的哪个方法:SOAPAction头或soap体中请求元素的名字。在这个例子中,每种方法都指出了发送者想调用的方法名。

.asmx句柄使用SOAPAction头的值来实现消息的分派。因此,.asmx句柄查看消息中的SOAPAction头,使用.NET映射检查引用类中的方法。它只考虑标记了[WebMethod]属性的方法,但通过查看每种方法的SOAPAction值再具体确定调用哪个方法。因为我们在类中并没有明确的指定SOAPAction的值,.asmx句柄认为SOAPAction的值是Web服务的名称空间加上方法名。而且我们也没有指定名称空间,所以句柄就把http://tempuri.org作为默认值。这样Add方法的默认SOAPAction值就是http://tempuri.org/Add。

可以按如下方法定制Web服务的名称空间。把类标记上[WebService]属性,用[SoapDocumentMethod]属性标记WebMethods来指定具体的SOAPAction值。示例如下:

using System.Web.Services;
using System.Web.Services.Protocols;
 
[WebService(Namespace="http://example.org/math")]
public class MathService
{
   [WebMethod]
   public double Add(double x, double y) {
      return x + y;
   }
   [WebMethod]
   [SoapDocumentMethod(Action="urn:math:subtract")]
   public double Subtract(double x, double y) {
      return x - y;
   }
   ...
}

现在.asmx句柄认为Add方法的SOAPAction值是http://example.org/math/AddSubTract的值是urn:math:subtract(因为我们在类中明确定义了)。比如下面的HTTP请求消息调用Subtract:
POST /math/math.asmx HTTP/1.1

Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "urn:math:subtract"
<soap:Envelope 
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
>
  <soap:Body>
    <Subtract xmlns="http://example.org/math">
      <x>33</x>
      <y>66</y>
    </Subtract>
  </soap:Body>
</soap:Envelope>

如果.asmx句柄没为HTTP请求消息找到一个SOAPAction匹配,将会抛出一个异常。如果你不想依赖SOAPAction头来分派消息,可以引导.asmx句柄使用请求元素名称。采用这种方法需要为类标记上[SoapDocumentService]属性的RoutingStyle特性,同时也应该指出WebMethods不需要SOAPAction值(在类中设定其值为空)。如下所示:

using System.Web.Services;
using System.Web.Services.Protocols;
 
[WebService(Namespace="http://example.org/math")]
[SoapDocumentService(
  RoutingStyle=SoapServiceRoutingStyle.RequestElement)]
public class MathService
{
   [WebMethod]
   [SoapDocumentMethod(Action="")]
   public double Add(double x, double y) {
      return x + y;
   }

[1] [2] [3] [4]  下一页

打印本文 打印本文 关闭窗口 关闭窗口