Example #1
0
        /// <summary>
        /// 请求过滤器
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            #region model验证处理
            if (!filterContext.Controller.ViewData.ModelState.IsValid)
            {
                var item  = filterContext.Controller.ViewData.ModelState.Values.ToList().Find(a => a.Errors.Count > 0);
                var error = item.Errors.Where(a => !string.IsNullOrEmpty(a.ErrorMessage)).Take(1).SingleOrDefault().ErrorMessage;
                filterContext.Result = new JsonResult
                {
                    Data = new { code = 1, msg = error },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
            #endregion

            #region 权限验证
            foreach (var item in filterContext.ActionDescriptor.GetCustomAttributes(true).ToList())
            {
                if (item is AllowAnonymousAttribute)
                {
                    return;
                }
            }

            var token = filterContext.HttpContext.Request["token"];
            if (!string.IsNullOrEmpty(token) && UserTokenManager.IsExistToken(token))
            {
                return;
            }
            else
            {
                filterContext.Result = new JsonResult
                {
                    Data = new { code = 13, msg = "登录凭证失效,获取数据失败!" },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
                return;
            }
            #endregion
        }
Example #2
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            // 验证token
            var ts = actionContext.Request.Headers.Where(c => c.Key.ToLower() == "token").FirstOrDefault().Value;

            if (ts != null && ts.Count() > 0)
            {
                var token = ts.First <string>();
                // 验证token
                if (!UTokenManger.IsExistToken(token))
                {
                    return(false);
                }
                return(true);
            }

            if (actionContext.Request.Method == HttpMethod.Options)
            {
                return(true);
            }
            return(false);
        }