gfreesky博客


    留下自己的脚印是一件很惬意的事:)
    博客园--美好愿望 美好生活......
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ASP.NET AJAX初学体验之客户端访问WebService(3)

Posted on 2008-10-28 21:51  gfreesky  阅读(344)  评论(0编辑  收藏  举报

本次要体验的是客户端访问WebService的原理与一些细节

思考1:Service有方法重载,那么客户端如何调用呢?

这时需要在Service方法的前面加标记,那如何标记呢?就是在WebMethod后面标记MessageName,而MessageName

的值就是你要在客户端访问的,看如下代码:

[ScriptService]
public class MethodOverloadedService  : WebService
{
    [WebMethod]
    
public int GetRandom()
    {
        
return new Random(DateTime.Now.Millisecond).Next();
    }
    
    
//客户端并不支持方法的重载,所以加MessageName标记
    [WebMethod(MessageName="GetRangeRandom")]
    
public int GetRandom(int minValue, int maxValue)
    {
        
return new Random(DateTime.Now.Millisecond).Next(minValue, maxValue);
    }
    
}

 

那客户端如何调用呢?看如下代码:

<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Debug">
            
<Services>
                
<asp:ServiceReference Path="Services/MethodOverloadedService.asmx" InlineScript="true" />
            
</Services>
        
</asp:ScriptManager>
        
        
<input type="button" value="Get Random" onclick="getRandom()" />
        
<input type="button" value="Get Range Random" onclick="getRandom(50, 100)" />
        
        
<script language="javascript" type="text/javascript">
            function getRandom(minValue, maxValue)
            {
                
if (arguments.length != 2)
                {
                    MethodOverloadedService.GetRandom(onSucceeded);
                }
                
else
                {
                    MethodOverloadedService.GetRangeRandom(minValue, maxValue, onSucceeded);
                }
            }
            
            function onSucceeded(result)
            {
                alert(result);
            }
        
</script>

 

因为2个按钮调用同一个方法,所以我们用arguments来进行判断,应该很好理解。
MethodOverloadedService.GetRangeRandom(minValue, maxValue, onSucceeded)这行的红色部分就是你
标记MessageName的值。

思考2:客户端发送数据默认采用的是HttpPost,那如果我想用HttpGet应该怎么做呢?

同样需要加标记,不过这次不是标记WebMethod而是ScriptMethod,看如下代码:

 //客户端发送数据默认采用的是HttpPost
    
//若想采用HttpGet则需要标记ScriptMethod的UseHttpGet属性
    [WebMethod]
    [ScriptMethod(UseHttpGet
=true)]
    
public int GetRangeRandom(int minValue, int maxValue)
    {
        
return new Random(DateTime.Now.Millisecond).Next(minValue, maxValue);
    }

 

ScriptMethod加标记,设置UseHttpGet=true就可以了哦,客户端调用代码不变。

思考3:客户端如何访问session?

这个问题你应该想到答案了,对的,还是加标记,给WebMethod标记
方法1:[WebMethod(true)]
方法2:[WebMethod(EnableSession=true)]

其他都一样了。

后续...