ASP.NET如何使用web服务的会话状态_asp.net教程-查字典教程网
ASP.NET如何使用web服务的会话状态
ASP.NET如何使用web服务的会话状态
发布时间:2016-12-29 来源:查字典编辑
摘要:在web服务中要用到ASP.NET中的会话对象,有2件事情需要做。1.WebService类需要继承System.Web.Services....

在web服务中要用到ASP.NET中的会话对象,有2件事情需要做。

1.WebService 类需要继承System.Web.Services.WebService类

2.WebMethod中的EnableSession属性值应该设置为true

来看我们CalculatorWebService类,我们可以看到,它已经继承System.Web.Services.WebService类。但是,我们需要EnableSession属性值设置为true。

本文中,我们将试试在使用一个如下所示的GridView中的会话对象来展示最近的计算结果.

为了达成这个目的,首先要想下面这样,修改CalculatorWebService类的Add方法.

[WebMethod(EnableSession = true)] public int Add(int firstNumber, int secondNumber) { List<string> calculations; if (Session["CALCULATIONS"] == null) { calculations = new List<string>(); } else { calculations = (List<string>)Session["CALCULATIONS"]; } string strTransaction = firstNumber.ToString() + " + " + secondNumber.ToString() + " = " + (firstNumber + secondNumber).ToString(); calculations.Add(strTransaction); Session["CALCULATIONS"] = calculations; return firstNumber + secondNumber; }

然后再引入另外一个公共方法来返回所有的计算结果. 要使用WebMethod特性来修饰这个方法,并且将EnableSession属性设置为true.

[WebMethod(EnableSession = true)] public List<string> GetCalculations() { if (Session["CALCULATIONS"] == null) { List<string> calculations = new List<string>(); calculations.Add("You have not performed any calculations"); return calculations; } else { return (List<string>)Session["CALCULATIONS"]; } }

现在就可以构建我们的解决方案了,并能在浏览器中查看到我们的Web服务.

Web服务会列出两个方法——Add和GetCalculations.

点击Add方法。让我们输入两个数字,比如20和30,然后点击Invoke按钮,我们会得到50这个结果.

让我们来做另外一次计算,比如30和70。然后点击Invoke按钮,我们将会得到结果为100.

现在让我们回头来测试一下我们的GetCalculation方法。然后点击Invoke方法,现在回展示出我们之前所做的所有计算。它们会以一个字符串数组的形式返回.

如此我们的Web服务就这样按照预期运作了。现在让我们来试试在我们的Web应用程序中使用这些方法。为此,在 Webform1.aspx 中, 让我们往其中拽一个GridView控件进去.

<tr> <td> <asp:GridView ID="gvCalculations" runat="server"> </asp:GridView> </td> </tr>

在文件修改之后的代码之前,我们需要更新一下代理类。为此,在CalculatorService并选择Update Service Reference.

此后,在btnAdd_Click事件代码段之中, 加入如下几行代码.

gvCalculations.DataSource = client.GetCalculations(); gvCalculations.DataBind(); gvCalculations.HeaderRow.Cells[0].Text = "Recent Calculations";

构建我们的解决方案,并在浏览器中查看这个web窗口.

让我们继续加入两个数字,比如20和30. 而我们会看到虽然我们已经执行了一次计算, You have not performed any calculations 这样的消息还是将会显示出来.

这基本上是因为web应用程序并没有像Web服务发送相同的SessionId。为此,将web.config文件中的allowCookie设置成true.

现在我们再来运行这个web窗口并添加一些数字。现在我们就可以看到它按照预期运行了.

因此,这下面有几点要深入思考:

如果Web服务被修改了,客户端应用程序的代理类就要被更新. 为此,在Service Reference夹下面的服务上点击右键,并选择Update Service Reference项.

将allowCookies属性设置成true,以便让客户端应用程序接受从ASMX Web服务返回的cookie,并将其复制到未来所有项Web 服务发起的请求中去. 这就确保了客户端和Web服务之间是维护的同一个Session。

如何使用web服务的会话状态,相信通过这篇文章大家应该有所了解了吧。

相关阅读
推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
  • 大家都在看
  • 小编推荐
  • 猜你喜欢
  • 最新asp.net教程学习
    热门asp.net教程学习
    编程开发子分类