UrlHelper and ViewContext inside an Authorization Attribute

Posted by DM on Stack Overflow See other posts from Stack Overflow or by DM
Published on 2010-04-18T06:58:21Z Indexed on 2010/04/18 7:03 UTC
Read the original article Hit count: 351

I have a scenario that I haven't been able to solve:

I'm toying around with creating my own custom authorization attribute for mvc. The main bit of functionality I would like to add is to have the ability to change where the user gets redirected if they are not in a certain role. I don't mind that the system sends them back to the login page if they're not authenticated, but I would like to choose where to send them if they are authenticated but not allowed to access that action method.

Here's is what I would like to do:

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
        public string Action;
        public string Controller;

        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            // if User is authenticated but not in the correct role
            string url = Url.Action(this.Action, this.Controller);                
            httpContext.Response.Redirect(url);
        }
    }

And as an added bonus I would like to have access to ViewContext and TempData before I do the redirect.

Any thoughts on how I could get instantiate a UrlHelper and ViewContext in the attribute?

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about ASP.NET