在VS2005中,Web服务代理的配置可以使用两种方法来自动完成,即引用Web服务自动完成,或者使用wsdl.exe工具自动完成。
Web服务代理用于客户端访问XML Web Services。在客户端使用Web引用时,VS2005将自动创建一个XML Web Services代理类,并把该类添加到项目中。
默认情况下,XML Web Services代理类使用静态的URL,指向引用XML Web Services的URL。当应用程序在web.config文件中指定了appSettings元素,Web服务代理可以从该元素指定的内容指向动态的URL。下面说明如何在web.config中指定appSettings元素,以指定XML Web Services代理的URL,代码如下:
<appSettings>
<add key ="myApplication.myserver.Service" value="http://myServer/myXmlWebService.asmx"/>
</appSettings>
下面分别说明如何使用这两种方法配置Web服务代理,步骤如下:
1、打开VS2005 ,创建一个ASP.NET 的Web服务网站,命名为“myXmlWebService”.
2、打开Services.cs文件,编辑该文件,代码如下:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace="http://tmpuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service()
{
}
[WebMothed(Description="Web服务代理测试方法",EnableSession=true)]
public string ServiceMethod()
{
return "Web 服务已调用。";
}
}
3、按F5运行该Web服务
4、保持myXmlWebService网站的运行状态,再次打开VS2005,创建一个asp.net网站应用程序,命名为“myWebApp”.
5、在myWebApp网站路径内添加Web引用,复制“myXmlWebService”运行网页上显示Service类操作类表的URL地址,粘贴到添加Web引用窗口的URL地址中,Web引用名保持“localhost”不变。
6、打开web.Config文件,VS2005为应用程序生成了appSetting节,代码如下:
<configuratioin>
<appSettings>
<add key="localhost.Service" value="http://localhost:1662/myXmlWebService/Service.asmx"/>
...
</appSettings>
7、在Default.aspx文件的设计界面上得空白处,双击鼠标左键,编写该页面的Page_Load事件处理方法。代码如下:
protected void Page_Load(object sender,EventArgs e)
{
Response.Write(new localhost.Service().ServiceMethod());
}
8、按F5运行网站应用程序,运行结果如下:
Web服务已调用。
9、在myXmlWebService网站解决方案中添加Web服务,命名为"wsdlService.asmx"。
10、在wsdlService.cs文件中编辑程序,代码如下
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
[WebService(Namespace="http://tmpuri.org/")]
[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service()
{
}
[WebMothed(Description="Web服务代理测试方法(wsdl)",EnableSession=true)]
public string ServiceMethod()
{
return "wsdl-Web 服务已调用。";
}
}
11、重新发布myXmlWebService网站,运行该网站。
12、保持myXmlWebService网站的运行,开发VS2005命令提示工具,进入myWebApp网站所在目录,运行一下命令:
wsdl.exe /appsettingurlkey:local.wsdlService "http://localhost:1662/myXmlWebService/wsdlService.asmx"
13、在myWebApp网站所在的目录下,添加asp.net文件夹App_Code,将前面生成的wsdlService.cs文件加入到该文件夹中。
14、在Default.aspx文件的设计界面上双击鼠标左键,编写Page_Load事件处理方法:
protected void Page_Load(object sender,EventArgs e)
{
Response.Write(new localhost.Service().ServiceMethod());
Response.Write(new wsdlService().wsdlServiceMehtod());
}
15、按F5运行程序,运行结果如下:
Web服务已调用。wsdl-Web服务已调用。
使用wsdl.exe生成的程序文件和WebService上的程序文件不同,该文件包含的类继承于SoapHttpClientProtocol类。在该类的构造函数中,使用appSettings中指定的URL创建类实例,如果appSettings没有指定URL,则使用默认的URL创建类实例。SoapHttpClientProtocol类包含实现SOAP交换信息协议的方法,通过这些方法,应用程序和Web服务能够进行多种方式的数据交换。