0

I am having an attibute

public class RequiresAdminRights : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            User user = User.Load(HttpContext.Current.User.Identity.Name);
            if (user != null)
            {
                if (!(user.IsInRole(Role.Administrator)))
                    throw new Exception("You need admin rights to access this resource.");
            }
        }
    }

In my controller I have

[Attributes.RequiresAdminRights]
public class UserController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

The user logged in doesnt have any admin right and the RequiresAdminRights throws an exception. How can I display the exception message?

goenning
  • 6,514
  • 1
  • 35
  • 42
learning
  • 11,415
  • 35
  • 87
  • 154
  • 1
    I wouldn't throw an exception but rather redirect the user to a page that either requires them to log in or presents them with an access denied message before redirecting them back to whence they came. – Lazarus Jan 28 '11 at 12:46
  • MY difficulty here is how and where to redirect the page, can I have an example please – learning Jan 28 '11 at 12:49

1 Answers1

0

Throw a custom exception like PermissionDeniedException, create a base Controller class and define like this.

[HandleError(ExceptionType = typeof(PermissionDeniedException), View = "Login")]]
public class BaseController : Controller
{

}

Your controller should now extend this class. Also, don't forget to turn On the customErrors in your web.config.

Now, everytime you throw and PermissionDeniedException the user will be redirected to "Login" View. Another option is to redirect the user to a "Permission Denied View" that will explain to your user that he needs to log in before accessing that page.

For more details you can check this other SO questions.

  1. ASP.NET MVC HandleError
  2. ASP.net MVC [HandleError] not catching exceptions
Community
  • 1
  • 1
goenning
  • 6,514
  • 1
  • 35
  • 42