在方法中使用Session
•ASP.NET中每个请求都由一个IHttpHandler对象来处理
•在处理时要使用Session则需要让Handler对象实现IRequiresSessionState接口
•RestHandlerFactory根据所请求的方法的标记来选择是否启用Session
•启用方法:在WebMethodAttribute中标记
–EnableSession属性设为true
aspx
EnableSessionService.asmx
•在处理时要使用Session则需要让Handler对象实现IRequiresSessionState接口
•RestHandlerFactory根据所请求的方法的标记来选择是否启用Session
•启用方法:在WebMethodAttribute中标记
–EnableSession属性设为true
aspx
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManager1" ScriptMode="Debug">
<Services>
<asp:ServiceReference Path="Services/EnableSessionService.asmx" InlineScript="true" />
</Services>
</asp:ScriptManager>
<input type="button" value="Add One" onclick="addOne()" />
<script language="javascript" type="text/javascript">
function addOne()
{
EnableSessionService.AddOne(onSucceeded);
}
function onSucceeded(result)
{
alert(result);
}
</script>
</form>
<asp:ScriptManager runat="server" ID="ScriptManager1" ScriptMode="Debug">
<Services>
<asp:ServiceReference Path="Services/EnableSessionService.asmx" InlineScript="true" />
</Services>
</asp:ScriptManager>
<input type="button" value="Add One" onclick="addOne()" />
<script language="javascript" type="text/javascript">
function addOne()
{
EnableSessionService.AddOne(onSucceeded);
}
function onSucceeded(result)
{
alert(result);
}
</script>
</form>
EnableSessionService.asmx
<%@ WebService Language="C#" Class="EnableSessionService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.SessionState;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class EnableSessionService : System.Web.Services.WebService
{
[WebMethod(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;
}
}
WebService方法加上[WebMethod(true)]修饰即可使用session
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Web.SessionState;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class EnableSessionService : System.Web.Services.WebService
{
[WebMethod(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;
}
}