WebApi 能支持Session

     因爲項目實際須要,我但願讓WebApi服務也能支持Session,因此便查找資料按照網上的方法開始着手實驗。web

     而後就有了如下的代碼,主要是說讓WebApi支持Session,要重寫Global.asax的Init方法api

    

public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configuration.EnableCors();
            GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
          
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
         
        }
      
        public override void Init()//重寫這個方法
        {
            PostAuthenticateRequest += MvcApplication_PostAuthenticateRequest;
            base.Init();
        }

        private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
        }
     
    }

  重寫方法後,準備動手編寫測試的Controller代碼 以下,很簡單的幾句代碼,A方法模擬第一次請求將攜帶的參數存入Session,其中鍵和值都爲傳入的參數appid,B方法是返回鍵爲appid的session的值。瀏覽器

 public class GetDataController : ApiController
    {
        
     
        [HttpGet]
        public void A(string appid)
        {

            System.Web.HttpContext.Current.Session[appid] = appid;
            System.Web.HttpContext.Current.Session.Timeout =1;
        }
        [HttpGet]
        public ResponseData B(string appid)
        {

            return new ResponseData() { data = System.Web.HttpContext.Current.Session[appid].ToString(), isSuccess = true };
        }
}

  用谷歌瀏覽器,模擬A\B兩個請求,實驗成功!!!!!非常高興!! cookie

    但問題來了,經過瀏覽器運行能夠取到session的值,可是在手機的移動設備端,訪問竟然每次獲取session的值都是null,有些不解,便開始尋找問題的根源所在,爲何瀏覽器正常,然而在移動設備模擬就不行了呢??????     功夫不負有心人,終於找到了問題所在,大概緣由就是說,session是靠一個的cookie來區分的,客戶端每次訪問要攜帶這個cookie才能保持session的狀態。因而我便用控制檯模擬移動端進行測試。代碼以下:session

class Program
    { 
        static void Main(string[] args)
        {

         
            GetMethod("http://192.168.1.9:8828/api/GetDAta/A?appid=abc");
             
         //  PostMethod("http://localhost:8828/api/GetDAta/Login/");
            Console.ReadKey();
            GetMethodTest("http://192.168.1.9:8828/api/GetDAta/b?appid=abc");
            Console.ReadKey();
        }
        private static CookieContainer m_Cookie = new CookieContainer();  
        private static void GetMethod(String url)
        {


            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = m_Cookie;
            string cookieheader = request.CookieContainer.GetCookieHeader(new Uri(url));
            m_Cookie.SetCookies(new Uri(url), cookieheader);  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {

                StreamReader reader = new StreamReader(response.GetResponseStream());
                Console.WriteLine(reader.ReadToEnd());
            }

        }
        private static void GetMethodTest(String url)
        {


            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.CookieContainer = m_Cookie;
            m_Cookie = request.CookieContainer;  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {

                StreamReader reader = new StreamReader(response.GetResponseStream());
                Console.WriteLine(reader.ReadToEnd());
            }

        }
}
GetMethod爲模擬訪問A服務,其中如下代碼,就是在訪問A的時候設置cookie
            request.CookieContainer = m_Cookie;
            string cookieheader = request.CookieContainer.GetCookieHeader(new Uri(url));
            m_Cookie.SetCookies(new Uri(url), cookieheader);  
GetMethodTest爲模擬訪問B服務,請求時候須要攜帶上次訪問A的cookie的信息,代碼以下
            request.CookieContainer = m_Cookie;
            m_Cookie = request.CookieContainer;  

   到此,一切測試完畢,正常運行。app

    初學webapi,哪有不對,但願園友多多指教!!!!!!!ide

相關文章
相關標籤/搜索