开发者

custom attribute to redirect based user object property (asp.net mvc)

I was using a custom authorize attribute, to restrict users without subscription from accessing some actions

public class IsSubscriptionActive : AuthorizeAttribute
{
    protec开发者_StackOverflow社区ted override bool AuthorizeCore(HttpContextBase httpContext)
    {
       //check if user logged in , if not return false
       //get user object from request
       if(UserObject.IsSubscriptionActive)
           return true;
       else
           return false;
    }
}

The problem here is that doing this redirects users to login page regardless of whether the user is logged in or not.

So, I want to use the default authorize attribute as it is, but have another attribute which will check for subscription status and redirect. How can I do this?


Not tested but try it out:

public class IsSubscribedAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.User.Identity == null || 
              !filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
             filterContext.Result = 
              new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl
                           + "?returnUrl=" + 
              filterContext.HttpContext.Server.UrlEncode
                           (filterContext.HttpContext.Request.RawUrl));
        }
        if (isSubscribed)//check subscription here.
        {
            filterContext.HttpContext.Response.StatusCode = 401;
            filterContext.Result = new HttpUnauthorizedResult();
        }//you can set the statuscode/result as you like?
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜