记录用户状态与过滤方法(过滤器使用)


一:几个常用对象


1:使用静态键值对

       一般在wcf接口中可以建立一个静态的键值对,用户登录后产生一个sessionid,把sessionid

      和用户id存放在键值对里,sessionid返回给前台,以后可以使用sessionid作为访问的凭证.

      静态键值对是所有用户共享一个类似application



2:使用cookie

       cookie是存放在客服端,针对单个用户的,也就是每次获取到的就是当前访问的用户,与其他用户不相关,

      可以存放一些不敏感的数据到cookie,记录用户的状态


3:使用session

       与cookie相似,针对单个用户,但是保存在服务器端,数据更安全


二:方法


1:每个Controller都继承一个基类,每个请求都必须要请求基类的一个方法,就可以过滤掉一些不正常的请求     

    public class BaseController : Controller
    {
        protected override IActionInvoker CreateActionInvoker()
        {
            if (this.GetType().Name != "LoginController")
            {
                //验证登陆
            }
            return base.CreateActionInvoker();
        }
    }

2: 使用过滤器    

public class IsLoginFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.RouteData.Values["controller"].ToString() != "Login")
            {
                //访问所有不是名称login的action都需要,验证登陆
                var session = filterContext.HttpContext.Session["IsLogin"];
                if (session == null) 
                {
                    filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { Controller = "Login", action = "Index" }));
                }
            }
            base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
        }
    }

  配置全局过滤器

  

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new IsLoginFilter());
        }
    注意可能会出现调用不明确,使用的是System.Web.Mvc里边的,不是System.Web


过滤器其他文章:

http://blog.csdn.net/u010096526/article/details/46700581







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值