Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)归海一刀published in(发表于) 2014/1/30 0:52:07 Asp.Net,Ajax,学习笔记8,客户端访问WebService(下)_[Asp.Net教程]
1、改变客户端访问WebService代理方法名
客户端无法重载函数,只能根据arguments的参数来判断。并且不能根据参数的类型来判断 如果WebService端有函数的重载,这时候映射到客户端是无法区别的。那么我们需要把函数的重载在客户端映射成非重载函数。在WebService方法上添加一个[WebMethod(MessageName = “…")]这样一个标记 [WebMethod]public int GetRandom(){ return new Random(DateTime.Now.Millisecond).Next();}
[WebMethod(MessageName="GetRangeRandom")]public int GetRandom(int minValue, int maxValue){ return new Random(DateTime.Now.Millisecond).Next(minValue, maxValue);}如例所示,那么有两个参数的GetRandom方法映射到客户端就是GetRangeRandom方法了。当然,不一定是重载时才能改变方法名,但是在重载时改变方法名才能体现这个标记的意义。 2、使用Http的Get方式访问WebService的方法
使用Get方式访问WebService的方法,必须加上[ScriptMethod(UseHttpGet=true)]标记 [WebMethod][ScriptMethod(UseHttpGet=true)]public int GetRangeRandom(int minValue, int maxValue){ return new Random(DateTime.Now.Millisecond).Next(minValue, maxValue);}参数将使用QueryString进行传递 性能较HTTPPOST方法略有提高 3、让方法返回XML对象
客户端调用WebService方法默认使用JSon字符串返回数据。 要返回XML对象必须给ScriptMethod标记加上ResponseForma=ResponseFormat.Xml参数 Response的Content-Type将被设置为text/xml 返回普通对象时将使用XmlSerializer输出,如上面例子中返回Employee 返回字符串时可以直接作为XML字符串输出,就是说就算给出XML结构类似的字符串,经过XmlSerializeString处理之后,会将<和>转义,并且根元素为string //输入的XML结构的字符串hello
//被XmlSerializeString处理后输出的字符串,根元素为string,<>被转义<xml>hello</xml>
4、在WebService方法中使用Session
在WebMethod标签中加入EnableSession=true参数 [WebMethod(EnableSession = true)]public int AddOne(){ HttpSessionState session = HttpContext.Current.Session; object objValue = session["value"]; int value = objValue == null ? 0 : (int)objValue; value++; session["value"] = value; return value;}5、在客户端调用WebService的安全性
完全适应Asp.Net的认证机制 可以使用FormsAuthentication,让WebService方法可以操作Cookie Impersonation PrincipalPermission 6、不使用WebService代理的对应方法,使用客户端代理直接调用WebService方法。
Invoke方法签名Sys.Net.WebServiceProxy.invoke= function (servicePath,/*Service路径*/methodName,/*方法名*/useGet,/*是否使用HTTPGET方法*/params,/*方法参数*/onSucceeded,/*成功后的回调函数*/onFailure,/*失败后的回调函数*/userContext,/*用户上下文对象*/timeout /* 超时时间*/){ } function getRandom(minValue, maxValue){ Sys.Net.WebServiceProxy.invoke( "Services/UseHttpGetService.asmx", "GetRangeRandom", true, { "minValue" : minValue, "maxValue" : maxValue}, onSucceeded, null, null, -1);}
对应上面的invoke参数说明和例子,对WebService生成的代理方法是如何调用WebService有一定了解
赞