【问题标题】:custom attribute to redirect based user object property (asp.net mvc)自定义属性重定向基于用户对象属性(asp.net mvc)
【发布时间】:2011-03-27 07:52:48
【问题描述】:

我正在使用自定义授权属性,以限制未订阅的用户访问某些操作

public class IsSubscriptionActive : AuthorizeAttribute
{
    protected 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;
    }
}

这里的问题是,无论用户是否登录,这样做都会将用户重定向到登录页面。

所以,我想按原样使用默认授权属性,但有另一个属性将检查订阅状态和重定向。 我该怎么做?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-2


    【解决方案1】:

    未测试但试一试:

    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?
        }
    }
    

    【讨论】:

    • 此代码原样重定向到登录页面。我在哪里可以设置自定义重定向操作或 url?
    • 请不要介意我对 ActionFilterAttribute 类的无知。是否可以执行类似 if(!isSubscribed) //redirect 的操作。这就是我要寻找的东西
    • 好的,我明白了。这是我现在的代码 if (user.IsSubscriptionActive) { filterContext.Result = new RedirectResult("/Account/Subscribe");}。可以吗,有什么需要改变的吗?
    猜你喜欢
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多