更新时间:2023-02-17 11:49:02
我能够通过编写自定义AuthorizeAttribute并将其用于应用程序中的每个类来实现此目的.在自定义授权属性中,我正在检查一个Claim,如果授权检查成功,该索赔将可用;如果未授权,则将用户重定向到一个单独的视图.
I was able to achieve this by writing custom AuthorizeAttribute and using it on every class in my application. In the custom authorize attribute I am checking for the a Claim which will be available if the authorization check is successful and redirecting the user to a separate view if not authorized.
public class CustomAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
if(UserClaims.PersonId == 0)
{
UrlHelper helper = new UrlHelper(filterContext.RequestContext);
string url = helper.Action("Unauthorized","Error",null,filterContext.HttpContext.Request.Url.Scheme);
filterContext.Result = new RedirectResult(url);
}
}
}
}