在ActionFilterAttribute对url进行判断并跳转至指定目录

55 55
C#
sam
sam 2024-10-04 18:23:31

1、定义filter:

MemberPcAuthenticationAttribute

代码

    public class MemberPcAuthenticationAttribute : ActionFilterAttribute
    {
        #region Overrides of ActionFilterAttribute

        /// <summary>
        /// 在执行操作方法之前由 MVC 框架调用。
        /// </summary>
        /// <param name="filterContext">筛选器上下文。</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //当前访问地址
            String currentUrl = RequestHelper.Url();

            MemberInfo loginMemberInfo = SourceCodeService.GetMemberLoginInfoForPc();

            //如果未登录则跳转至登录页
            if (loginMemberInfo == null)
            {
                filterContext.Result =
                    new RedirectResult("/login/index?returnUrl=" + HttpUtility.UrlEncode(currentUrl));

                //filterContext.HttpContext.Response.Redirect("/login/index?returnUrl=" + HttpUtility.UrlEncode(currentUrl));
                //return;
            }

        }

        #endregion
    }

这里需要注意使用filterContext的result来定义相关的返回值,不能使用 filterContext.HttpContext.Response.Redirect("/login/index?returnUrl=" + HttpUtility.UrlEncode(currentUrl));

这里需要注意一下

回帖
  • 消灭零回复