【记录】ASP.NET MVC AuthorizeAttribute OnAuthorization 验证跳转

时间:2021-05-03 14:49:47

重写 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();
}
}
}