ASP.NET MVC AuthorizeAttribute OnAuthorization 验证跳转<转载>

重写 AuthorizeAttribute 的 OnAuthorization 方法:

using System.Web.Mvc;

namespace Demo.Web.Common
{
    public class AuthorizeUserAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                return;
            }
            if (!Demo.ExternalService.UserService.IsUserInRole(filterContext.HttpContext.User.Identity.Name))
            {
                filterContext.Result = new RedirectResult("http://www.test.com");//身份验证不通过,则跳转至此网站。
            }
        }
    }
}

Controller 控制器配置:

using System.Web.Mvc;

namespace Demo.Ad.Web.Controllers
{
    [AuthorizeUser]//可以在 Controller 上直接配置,作用于此 Controller 下所有 Action
    public class IndexController : Controller
    {
        //[AuthorizeUser]
        public ActionResult Index()
        {
            return View();
        }
    }
}
原文地址:https://www.cnblogs.com/kiven36/p/4462285.html