本次要体验的是客户端访问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);
}
}
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>
<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);
}
//若想采用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)]
其他都一样了。
后续...