特性Attribute 的使用

  [IdentityAuthorize]   
        public ActionResult Index()
        {
            return View("~/Views/Index.cshtml");
        }

 

  [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
    public class IdentityAuthorizeAttribute : ActionFilterAttribute, IActionFilter
    {
        /// <summary>
        /// 验证是否登陆,没有登陆跳转到 登陆页
        /// </summary>
        /// <param name="filterContext">上下文</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            try
            {
                if (!Identity.IsAuthenticated)
                {
                    string url = HttpContext.Current.Request.Url.ToString();
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.Write("<script>window.top.location='" + Config.WapLoginUrl + "?backurl=" + url + "'</script>");
                    HttpContext.Current.Response.End();
                }
                base.OnActionExecuting(filterContext);
            }
            catch (Exception exception)
            {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write(exception.Message);
                HttpContext.Current.Response.End();
            }
        }
    }

你可能感兴趣的:(attribute)