龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

学习ASP.NET的WebServices调用方法(3)

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
5. SoapHeader SoapHeader 多数情况下用来传递用户身份验证信息,当然它的作用远不止如此,有待于在实际应用中发掘。 SoapHeader 缺省情况下由客户端代理对象

5. SoapHeader

SoapHeader 多数情况下用来传递用户身份验证信息,当然它的作用远不止如此,有待于在实际应用中发掘。

SoapHeader 缺省情况下由客户端代理对象发送给 WebService,当然我们可以通过 WebMethodAttribute.Direction 来改变传送方向。

SoapHeader 使用步骤:

(1) 创建继承自 System.Web.WebServices.SoapHeader 的自定义 SoapHeader 类型。
(2) 在 WebService 中创建拥有 public 访问权限的自定义 SoapHeader 字段。
(3) 在需要使用 SoapHeader 的 WebMethod 上添加 SoapHeaderAttribute 访问特性。SoapHeaderAttribute 构造必须指定 memberName 参数,就是我们在第二步中申明的字段名称。
(4) 生成器会自动为客户端生成同名的自定义 SoapHeader 类型,只不过比起我们在 WebService 端创建的要复杂一些。同时还会为代理类型添加一个 soapheaderValue 属性。

在下面的演示代码,客户端将传递一个自定义 MyHeader 到 WebService。请注意,我们尽管在 WebService 中申明了 MyHeader 字段,但并没有创建对象实例,这是因为客户端传递过来的 XML 中包含了 SoapHeader 信息,基础结构会自动解析并创建对象实例,然后赋值给 my 字段。至于客户端,自然需要创建一个 MyHeader 对象实例,并赋值给 WebService.MyHeaderValue 属性。SoapHeaderAttribute.Direction 缺省就是 In,下面例子中的 "Direction = SoapHeaderDirection.In" 可以省略。

WebServices.cs

public class MyHeader : SoapHeader
{
   public string Username;
   public string Password;
}

[WebService(Namespace = "http://www.rainsts.net/", Description="我的Web服务")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
   public MyHeader my;

   [WebMethod]
   [SoapHeader("my", Direction = SoapHeaderDirection.In)]
   public void TestSoapHeadIn()
   {
     System.Diagnostics.Debug.Write(my.Username);
     System.Diagnostics.Debug.Write(my.Password);
   }
}


Client.cs

WebService ws = new WebService();

MyHeader head = new MyHeader();
head.Username = "u2";
head.Password = "p2";

ws.MyHeadValue = head;
ws.TestSoapHeadIn();


我们改写一下,将传递方向改为从 WebService 到客户端。自然我们需要调整 "Direction = SoapHeaderDirection.Out",在 WebMethod 中我们还必须创建 MyHeader 实例,因为这次我们不会接受到客户端传递的 SoapHeader 了。客户端代理对象调用 WebMethod 后就可以使用 MyHeaderValue 属性访问其内容了。

WebServices.cs

public class MyHeader : SoapHeader
{
   public string Username;
   public string Password;
}

[WebService(Namespace = "http://www.rainsts.net/", Description="我的Web服务")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
   public MyHeader my;

   [WebMethod]
   [SoapHeader("my", Direction = SoapHeaderDirection.Out)]
   public void TestSoapHeadOut()
   {
     my = new MyHeader();
     my.Username = "u1";
     my.Password = "p1";
   }
}


Client.cs

WebService ws = new WebService();
ws.TestSoapHeadOut();

Console.WriteLine(ws.MyHeaderValue.Username);
Console.WriteLine(ws.MyHeaderValue.Password);


精彩图集

赞助商链接