Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/1/30 0:52:03
Asp.Net,Ajax,学习笔记6,客户端访问WebService(上)_[Asp.Net教程]

Asp.Net Ajax 学习笔记6 客户端访问WebService(上)_[Asp.Net教程]

1、要客户端能访问WebService,那么WebService类必须加上[ScriptService]标记,此标记在System.Web.Script.Services命名空间下,并且被访问的方法必须是public和加上[WebMethod]标记。客户端在ScriptManager标签之间加上如下代码


InlineScript属性表示是否将代理缓存到页面中(HTML源码中)。在js代码调用WebService时,如果WebService有命名空间,必须加上命名空间调用,并且WebService里面方法是作为静态方法调用,也就是说,不用实例化WebService。在客户端调用WebService的方法的时候,ScriptManager代理的方法后默认追加几个参数个参数,


注意,即使没有返回值也会调用回调函数。


2、客户端访问页面的方法。页面的方法必须写在aspx页面文件对应的aspx.cs文件上。方法必须是public和static并且用[WebMethod]标记。客户端必须使用PageMethods.方法名()访问,并且与访问WebService一样有成功后的回调函数。注:ScriptManager的EnablePageMethods属性必须设置为true,才能访问页面的方法。一般很少使用客户端访问页面的方法。


3、调用PageMethod和WebService的错误处理。如第一点所描述的失败回调函数的参数为一个error对象,那么错误对象有一下几种方法,来返回错误的一些信息WebService方法:


[WebMethod]
public Employee DoubleSalary(Employee employee)
{
employee.Salary *= 2;
return employee;
}
Employee类:


public class Employee
{
public string FirstName;


public string LastName;


public int Salary;


public string FullName
{
get
{
return this.FirstName + " " + this.LastName;
}
}
}
那么客户端的employee对象,因为与Employee的公开字段相同名字的Field,并且WebMethod的方法是Employee类,那么,调用WebMethod的方法的时候employee对象由客户端的Object类型转换为了Employee类型。那么返回值也与此类似,只不过转换方向反过来了。


容器对象:在WebService一方要返回一个集合或参数是一个集合,那么这个方法的返回值或参数必须实现了IList接口或IDictionary接口的对象。并且IDictionary对象的key必须是string类型,那么客户端的对象一定是Array类型。这样就能实现由客户端的Array类型到服务段的IList或IDictionary类型的互转


注:Array类型可以象IList接口是一个一维数组,也可以是类似与IDictionary是一个带有key的二位数组



error.get_timedOut()
error.get_message()
error.get_exceptionType()
error.get_stackTrace()
生成的WebService代理存在一个set_timeout()方法,用来设置调用WebService的超时时间。PageMethod不存在这个方法。


4、负责类型的使用


公有属性或公有Field会被释放和接受。这句话的意思就是如果通过客户端传递过来的对象,这个对象的属性与WebService里方法参数所对应的类的公有属性或公有Field字段名相同,将自动转换为相应的对象。如以下代码


客户端:


function doubleSalary()
{
var employee = new Object();
employee.FirstName = "Jeffrey";
employee.LastName = "Zhao";
employee.Salary = 1000;
ComplexType.DoubleSalary(employee, doubleSalarySucceeded);
}


WebMethod(arg1, …, argN, onSucceeded, onFailed,userContext)
onSucceeded:执行成功调用的回调函数地址


onSucceeded(result, userContext, methodName)
onSucceeded的三个参数:result函数的返回值,userContext是有调用WebMethod的userContext,可以将一些附加信息传递到onSucceeded函数,methodName调用成功回调函数的的WebMethod的函数名。


onFailed:执行失败/超时的回调函数地址


onFailed(result, userContext, methodName)
onFailed的三个参数:result是error对象,后面两个参数与onSucceeded的两个参数相同。


userContext:由用户指定要传给回调函数的附加信息


WebService方法生成的代理方法最后三个参数可以通过以下几个方法


WebService.set_defaultUserContext(information)
WebService.set_defaultSucceededCallback(functionName)
WebService.set_defaultFailedCallback(functionName)







If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759