一般處理程序獲取Session方式


  今天寫程序得時候遇到了一個問題:ajax在對ashx進行請求時如果按照 context.Request方式直接來獲取值得話獲取到得是空值,因此去網上搜了一下問題。現記錄如下:

  ashx獲取session值:

  1.首先添加引用:using System.Web.SessionState;

  2.我們得一般處理程序類要繼承IRequiresSessionState接口

  3.對session值判斷是否為null

  4.使用context.session["***"] 得到對應得session值

  下面寫一個例子測試一下:

  html代碼:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title>測試界面</title>
 6     <script src="javascript/jquery-1.11.1.min.js"></script>
 7     <style>
 8     </style>
 9     <script>
10         //測試ajax向后台獲取信息
11         function getinfo() {
12             $.ajax({
13                 url: "ashx/Handler1.ashx?action=get",
14                 dataType: "text",
15                 success: function (data) {
16                     alert(data);
17                 },
18             })
19         }
20         function setsession() {
21             $.ajax({
22                 url: "ashx/Handler1.ashx?action=set",
23             })
24         }
25         window.onload = function () {
26             setsession();
27             getinfo();
28         }
29     </script>
30 </head>
31 <body>
32     <div id="test">
33     </div>
34 </body>
35 </html>

 

  ashx代碼:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.SessionState;
 6 namespace Biobase_BigData.ashx
 7 {
 8     /// <summary>
 9     /// Handler1 的摘要說明
10     /// </summary>
11     public class Handler1 : IHttpHandler, IRequiresSessionState
12     {
13 
14         public void ProcessRequest(HttpContext context)
15         {
16             context.Response.ContentType = "text/plain";
17             string action = "";
18             if (context.Request.QueryString["action"] != null)
19             {
20                 action = context.Request.QueryString["action"].ToString();
21             }
22             switch (action)
23             {
24                 case "get":
25                     string session = "";
26                     if(context.Session["name"]!=null){
27                          session = context.Session["name"].ToString();
28                     }
29                     context.Response.Write(session);
30                     break;
31                 case "set":
32                     context.Session["name"] = "ceshi";
33                     break;
34             }
35         }
36 
37         public bool IsReusable
38         {
39             get
40             {
41                 return false;
42             }
43         }
44     }
45 }

  運行結果顯示:

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM