我正在尝试修改MVC中Controller方法的[Authorize]标签。我找到了许多声称正在工作的例子。这是代码:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeRedirect : AuthorizeAttribute
{
private const string IS_AUTHORIZED = "isAuthorized";
public string RedirectUrl = "~/error/unauthorized";
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
bool isAuthorized = base.AuthorizeCore(httpContext);
httpContext.Items.Add(IS_AUTHORIZED, isAuthorized);
return isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
var isAuthorized = filterContext.HttpContext.Items[IS_AUTHORIZED] != null
? Convert.ToBoolean(filterContext.HttpContext.Items[IS_AUTHORIZED])
: false;
if (!isAuthorized && filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.RequestContext.HttpContext.Response.Redirect(RedirectUrl);
}
}
}
我将此代码作为Class添加到HomeController类中,并将标记添加到方法中:
[AuthorizeRedirect]
public ActionResult Devices()
{
return View();
}
当我尝试将unAuthorized转到设备视图时,我不会被重定向到/ error / unauthorized。 我使用returnurl参数重定向到常规帐户/登录。
我做错了什么?
答案 0 :(得分:0)
从代码中删除此行: base.OnAuthorization(filterContext);