ASP.NET Web Service如何工作(3)
为了使.asmx句柄有可能反串行化SOAP头,首先你需要定义一个.NET类,它代表了暗含的XML Schema类。在此例中相应的类如下:
[XMLType(Namespace="http://example.org/security")]
[XMLRoot(Namespace="http://example.org/security")]
public class UsernameToken : SoapHeader {
public string username;
public string password;
}
然后你需要在WebMethod类中定义一个成员变量来控制一个头类的实例,同样要为WebMethods标记[SoapHeader]属性。见如下:
using System;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace="urn:geometry")]
public class Geometry {
public UsernameToken Token;
[WebMethod]
[SoapHeader("Token")]
public double Distance(Point orig, Point dest) {
if (!Token.username.Equals(Reverse(Token.password)))
throw new Exception("access denied");
return Math.Sqrt(Math.Pow(orig.x-dest.x, 2)
Math.Pow(orig.y-dest.y, 2));
}
}
这样,在WebMethod中你可以访问Token域,并提取SOAP头提供的信息。你也可以使用同样的技术将头信息送回客户端——你需要在[SoapHeader]属性声明中指定头的方向。
.asmx句柄也提供了.NET异常的自动串行化。任何被.asmx句柄劫获的未处理的异常都会被自动串行化为应答消息中的SOAP Fault元素。比如,在前面的例子中,假如用户名与反转的口令不匹配,我们的代码将会抛出一个.NET异常。.asmx句柄劫获这个异常,将它串行化为下面的SOAP应答:
<soap:Envelope
XMLns:soap="http://schemas.XMLsoap.org/soap/envelope/"
>
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Server was unable to process request. --