三、asp+web服务
1).介绍
当今的web已经不再是提供访问了。
ngws对asp+提供了创建web服务的内在支持。
web服务文件以.asmx结尾,也是在一个web应用中,也用uri寻址,一个简单例子:
<%@ webservice language="c#"%>
using system.web.services;
public class helloworld:webservice{
[webmethod]
public string sayhelloworld(){
return "helloworld";
}
}
用webservice指令标记,引入名称空间system.web.services,类从webservice派生,
[webmethod]签署后面的方法保护给外部(如果用vb,则为<webmethod>)。
访问:http://localhost/helloworld.asmx,可以使用多种协议,包括soap,http get等。
如果带参数?sdl,如helloworld.asmx?sdl,则返回xml格式,基于sdl文件格式的一个描述信息。
sdl(service description language).
ngws带有工具创建web服务应用。客户访问web服务需要一个能懂得sdl文件格式的代理类,
ngws提供工具webserviceutil.exe以创建这个代理类。
例: webserviceutil /c:proxy /pa:http://localhost/helloworld.asmx?sdl
创建了一个 helloworld.cs文件。这个文件跟先前的类很相似,也有相同的方法([webmethod]
签署的方法),编译它,然后调用其中的方法,它将通过soap协议访问服务器上的类,然后返回
结果(呵呵,很像java中的rmi,或者原来的dcom)。
2).编写简单的web服务
<%webservice language="c#" %>
using system;
using system.web.services;
public class mathservice{
[webmethod]
public int add(int a,int b){
return a+b;
}
[webmethod]
public int subtract(int a,int b){
return a-b;
}
}
直接在浏览器里调用mathservice.asmx,将显示一个介绍页面,介绍了web服务能提供的服务
以及参数。如果带上参数?sdl访问,则返回一个sdl内容。
如果想把一个事先写好的类改成一个web服务,只需要另建一个asmx文件,且只有一行:
<%@ webservice class="mywebapplication.mywebservice"%>
注意,因为服务也支持http get方式访问,所以我们可以直接在浏览器里测试我们的服务,
比如:
<form action="http://localhost/mathservice.asmx/add">
<input type="text" name="a">
<input type="text" name="b">
<input type=submit value="加">
</form>
3).web服务的类型
soap支持的可作为参数或返回值的类型有:
简单类型,如string,int32,boolean,single等
列举类型,比如public enum color{red=1,blue=2}
简单类型或列举类型的数组
类和结构体,其属性或字段将被序列化以传输。
类数组
dataset(ado+中的dataset),如果子类化dataset,则不保险
dataset数组
xmlnode及其数组
参数即可传值,也可传引用(这一点比rmi强)。
如果用http协议,仅支持:
简单类型中的一部分
列举
简单类型或列举的数组
其实,http协议传递时都是传的串么,这一点我们大家都很清楚。
如果在同一个asmx文件中定义了多个类,则需要在webservice中指定将哪一个作为web服务,
如:<%@ webservice language="c#" class="datatypes"%>
4).在web服务中访问数据
然后用xml格式返回给客户,客户再重造表结构,如:
[webmethod]
public dataset gettitleauthors(){
…..
dataset ds = new dataset();
……
return ds;
}
客户:
dataservice d = new dataserveice();
dataset mydata = d.gettitleauthors();
5).使用对象和属性
略
[webmethod(enablesession=false)]可以关闭session,以提高性能。
