WebApi 能支持Session

     由于项目实际需要,我希望让WebApi服务也能支持Session,所以便查找资料按照网上的方法开始着手实验。

     然后就有了以下的代码,主要是说让WebApi支持Session,要重写Global.asax的Init方法

    

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两个请求,实验成功!!!!!很是高兴!! 

    但问题来了,通过浏览器运行可以取到session的值,但是在手机的移动设备端,访问居然每次获取session的值都是null,有些不解,便开始寻找问题的根源所在,为什么浏览器正常,然而在移动设备模拟就不行了呢??????     功夫不负有心人,终于找到了问题所在,大概原因就是说,session是靠一个的cookie来区分的,客户端每次访问要携带这个cookie才能保持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;  

   到此,一切测试完毕,正常运行。

    初学webapi,哪有不对,希望园友多多指教!!!!!!!

 
 

 

posted @ 2015-09-28 09:59  沈阳晓东  阅读(1853)  评论(0编辑  收藏  举报