我正在尝试创建自定义Authorize属性来执行以下操作:
这是用户尝试打开搜索控制器的时间。我做了这样的自定义Authorize属性:
public class DenyRegularUser : System.Web.Mvc.AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("~/User/Logon");
return;
}
if (filterContext.HttpContext.User.IsInRole("Regular user"))
{
filterContext.Result = new RedirectResult("~/Index/Subscribe");
}
}
}
这是我的搜索控制器:
namespace WebApplication2.Controllers
{
[DenyRegularUser(Roles ="Regular user")]
public class SearchController : Controller
{
// GET: Search
public ActionResult Index()
{
return View();
}
}
}
但出于某种原因,即使我将用户的角色从普通用户更新为管理员或订阅者,我也会被重定向到登录页面:/ user / login ...
这不应该发生,因为登录功能完美运行,我得到了用户的角色......
我错过了什么?
答案 0 :(得分:0)
这可能有所帮助。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class DenyRegularUser : AuthorizeAttribute
{
public DenyRegularUser() :
base()
{
}
protected override bool IsAuthorized (System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (AuthorizeRequest(actionContext))
{
return true;
}
return false;
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Code to handle unauthorized request
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.TemporaryRedirect);
actionContext.Response.Headers.Add("Location", "~/Index/Subscribe");
}
private bool AuthorizeRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Write your code here to perform authorization
}
}
我相信IsAuthorized方法是覆盖AuthorizeAttribute的正确方法。