WebAPI——cookie与session遇到的问题

来源:互联网 发布:轰炸机软件 编辑:程序博客网 时间:2024/06/08 09:14

      这两天要做一个用户登陆验证的接口,用MVC这种action和view结合的做的话比较好做,但是直接使用webapi做的过程中遇到了不少困难,这里和大家分享一下==

一、WebAPI中session与cookie操作


由于两者用的框架不一样,当然webapi有自己的操作方法。

            string user = HttpContext.Current.Request["user"];            //string pw = HttpContext.Current.Request["pw"];            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["user"];            //没有cookie            if (cookie == null)            {                //用户正确                if (user.Equals("xcy"))                {                    //设置客户端cookie                    cookie = new HttpCookie("user");                    cookie.Domain = Request.RequestUri.Host;                    cookie.Path = "/";                    cookie.Values["user"] = user;                    //cookie.Values["user2"] = user;                    //cookie.Values.Add("user", user);                    //设置服务端session                    //HttpContext.Current.Response.Cookies[""]                    HttpContext.Current.Response.AppendCookie(cookie);                    HttpContext.Current.Session["user"] = user;                    return Ok("登陆成功");                }                //用户不正确                else                {                    return Ok("用户名不对");                }            }            //有cookie            else            {                string session = HttpContext.Current.Session["user"].ToString();                string co = cookie.Values["user"];                if (co.Equals(session))                {                    return Ok("登陆成功");                }                else                {                    return Ok("登陆已过期");                }            }

代码逻辑性就不要看了,直接看看操作方法就ok。


二、用户登录验证思路


第一种(基于session):

      初次登陆时通过数据库验证,验证成功则在session中保存用户名“user”;

      以后每次其他页面使用的时候要进行session判断看其中user是否有变量,有的话则默认进入页面,没有的话直接返回登录界面;

第二种(基于cookie):

      初次登陆的时候通过数据库验证,验证成功则在cookie中设置user,让浏览器每次带着它返回(设置cookie生命周期还没找到);

      第二次登陆的时候获取cookie看user是否有值,有的话则登陆成功,没有的话则返回登录界面;

第三种(第一种session的延伸)

      原理基本和第一种一样,但是不是用session保存,为了不同服务器数据的共享,保存在数据库memcache中;

我采用的是第一种,比较简单,而且性能要求也没那么高,在MVC的WebApi中默认是没有开启Session会话支持的。需要在Global中重写Init方法来指定会话需要支持的类型

        public override void Init()        {            this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);            base.Init();        }


三、webapi过滤器和mvc过滤器的区别


在各个页面使用登录验证的时候都添加太麻烦,所以过滤器要派上用场。

这是mvc中的几种过滤器


webapi中的过滤器类似使用方法并不完全相同。

当时我自己创建了一个过滤器如下

 public class MyActionFilterAttribute: ActionFilterAttribute    {        public string name { get; set; }        //public override void OnActionExecuting(ActionExecutingContext filterContext)        //{        //    base.OnActionExecuting(filterContext);        //    filterContext.HttpContext.Response.Write("开始时间:" + DateTime.Now.ToString() + name+"<br/>");        //}        //public override void OnActionExecuted(ActionExecutedContext filterContext)        //{        //    base.OnActionExecuted(filterContext);        //    var controllerName = filterContext.RouteData.Values["controller"].ToString();        //    var actionName = filterContext.RouteData.Values["action"].ToString();        //    filterContext.HttpContext.Response.Write("结束时间:" + DateTime.Now.ToString() + "<br/>");        //    filterContext.HttpContext.Response.Write("controller:" + controllerName + ",action:" + actionName);        //}        //public override void OnResultExecuting(ResultExecutingContext filterContext)        //{        //    base.OnResultExecuting(filterContext);        //    filterContext.HttpContext.Response.Write("开始时间:" + DateTime.Now.ToString() + "<br/>");        //}        //public override void OnResultExecuted(ResultExecutedContext filterContext)        //{        //    base.OnResultExecuted(filterContext);        //    filterContext.HttpContext.Response.Write("开始时间:" + DateTime.Now.ToString() + "<br/>");        //}        public override void OnActionExecuting(HttpActionContext actionContext)        {            base.OnActionExecuting(actionContext);            Debug.WriteLine("ACTION 1 DEBUG pre-processing logging");            //actionContext.Response.        }        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)        {            base.OnActionExecuted(actionExecutedContext);            Debug.WriteLine("ACTION 1 DEBUG  OnActionExecuted Response " + actionExecutedContext.Response.StatusCode.ToString());        }    }

      filter触发不了 ,写了一个filter的例子,继承actionfilterattribute,死活触发不了。搞了半天后来才搞明白,filter 继承了mvc4的。原来webapi 在system.web.http命名空间下,mvc在System.web.mvc下,两个空间都有filter,不知道怎么搞得,继承mvc的了。上面注释代码是继承mvc时使用的代码==


四、登录界面保存的session获取不到


      这个把我都快搞炸了,后来分析后发现每次验证的时候request中cookie值都没有,分析了一下是不是跨域的问题,后来改调试模式为上线模式(我调试的时候前后端分开的),问题就好了===但是如何让cookie在跨域的时候也包含到request里面还没弄太清楚,貌似只有html和webservice在一个服务器上才可以==


      初次涉及到用户验证,理解不是很深入,一知半解分享给大家,不明白的地方求大牛指点==

0 0
原创粉丝点击