asp.net mvc 过滤器基本方法

 

asp.net mvc里的过滤器是个非常好用的东西,用来做登录和权限验证是最常规的用法,里面有些具体实现方法,查找资料比较困难,现在把一些常用到的记录一下,供大家参考:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class LoginFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var session = filterContext.HttpContext.Session;
            var request = filterContext.HttpContext.Request;
            var response = filterContext.HttpContext.Response;
            var user = session["Account"] as Account;
            if (user == null)
            {//未登陆,判断是否有记住登录
                var token = Cookies.ReadCookie("remembermetoken");
                Guid r = Guid.Empty;
                if (Guid.TryParse(token, out r))
                {
                    var account = Account.GetAccountByRememberMeToken(r);
                    if (account == null)
                    {
                        if (string.IsNullOrWhiteSpace(request["submitTime"]))
                        {
                            session.Clear();
                            Cookies.DeleteCoookie();
                            filterContext.Result = new JsonResult() { Data = new ReturnMsg(MessageType.LoginExpire) };
                        }
                        else
                        {
                            filterContext.Result = new RedirectResult(request.Url.Scheme + "://" + request.Url.Authority);
                        }
                    }
                    else
                    {//remember me 功能实现
                        //这里没有做会员过期判断,以后可能会根据情况加上
                        session["AccountId"] = account.id.ToString();
                        session["Account"] = account;
                        filterContext.Controller.ViewBag.User = account;
                    }
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(request["submitTime"]))
                    {
                        filterContext.Result = new RedirectResult(request.Url.Scheme + "://" + request.Url.Authority);
                    }
                    else
                    {
                        filterContext.Result = new JsonResult() { Data = new ReturnMsg(MessageType.LoginExpire) };
                    }
                }
            }
            else
            {
                filterContext.Controller.ViewBag.User = user;
            }
        }
        [ValidateInput(false)]
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var request    = filterContext.HttpContext.Request;
            var session    = filterContext.HttpContext.Session;
            var controller = filterContext.RouteData.Values["action"].ToString();
            var action     = filterContext.RouteData.Values["controller"].ToString();
            var model      = session["Account"] as Account;

            var log    = new VisitLog();
            log.IP     = HttpHelper.GetRealIPFromRequest(request);
            log.Url    = request.Url.AbsoluteUri;
            log.module = controller;
            log.page   = action;
            var pm     = "";
            for (int i = 0; i < request.Form.Count; i++)
            {
                pm += "&" + request.Form.Keys[i] + "=" + request.Form[i].Trim();
            }
            if (model != null)
            {
                log.AccountId = model.id;
            }
            log.Param = pm.Trim('&');
            log.Method = request.HttpMethod;
            VisitLog.Add(log);
        }
    }

 

这一小段代码,字字玑珠,内容丰富,包含过滤器内获取asp.net内置对象的方法,获取控制器和目标方法名称,如何重定向以及阻断返回json等,还有登录验证逻辑,访问日志记录,  返回首页,rememberme功能实现等,可以作为一个过滤器使用的典范了^_^

 

 

 

你可能感兴趣的:(MVC项目规范)