在上次博客帖子中,我們討論了客戶端對web服務的使用。在這篇文章中我們將復習一下如何使用web服務的會話狀態。
這是上一篇文章的延續。因此請迅速的回顧之前的文章以便有一個清晰的概念。
在web服務中要用到ASP.NET中的會話對象,有2件事情需要做。
1.WebService 類需要繼承System.Web.Services.WebService類
2.WebMethod中的Enablesession屬性值應該設置為true

來看我們CalculatorWebService類,我們可以看到,它已經繼承System.Web.Services.WebService類。但是,我們需要EnableSession屬性值設置為true。
本文中,我們將試試在使用一個如下所示的GridView中的會話對象來展示最近的計算結果.

為了達成這個目的,首先要想下面這樣,修改CalculatorWebService類的Add方法.
| 12345678910111213141516171819202122 | [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.
| 1234567891011121314 | [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控件進去.
| 123456 | <tr><td><asp:GridView ID="gvCalculations" runat="server"></asp:GridView>學習交流
熱門圖片
猜你喜歡的新聞
新聞熱點 2019-10-23 09:17:05
2019-10-21 09:20:02
2019-10-21 09:00:12
2019-09-26 08:57:12
2019-09-25 08:46:36
2019-09-25 08:15:43
疑難解答 |