1

I'm trying to create custom error pages for a MVC 4 application. But I can't seem to find proper reference material to learn about it.

I have a specific requirement. It's to do with Unauthorized access error. Say I have a set of pages which is only accessible to certain type of users. User typed Admin is authorized to access the admin page but the User typed Basic is not.

So what I want to do is, if the user who's type is Basic is logged into the website and if they try to visit the admin page, instead of throwing them to the login page show them a message in an error page.

Can anyone help me with how to achieve this?

Amila
  • 3,501
  • 3
  • 22
  • 35

1 Answers1

1

How about an exception filter?

 [HandleError(Exception = typeof(UnauthorizedAccessException), View = "MyErrorPage")]
 public class MyController { }

I can't test this at the moment, if this doesn't work let me know and I'll create a custom filter for this purpose.

UPDATE

Since you've created your own custom attribute, you would pass information to your view from your attribute via TempData:

 public void OnAuthorization(AuthorizationContext filterContext)
 {
     //Note you could assign a complex type here, let's just assign a string
     filterContext.Controller.TempData["ErrorDetails"] = "Here are my details"; 

     // Redirect to an "Unauthorized" controller
     filterContext.HttpContext.Response.Redirect(urlHelper.Action("Index", "Unauthorized"), true);
Mister Epic
  • 15,703
  • 11
  • 68
  • 126
  • thanks for your reply. I tried your answer, but it didn't work. I have a custom authorize attribute. so this unauthorized access error page should only show if the user is already logged in but not authorized to view the content. so I used a method mentioned in here http://stackoverflow.com/questions/355700/asp-net-mvc-public-alternative-to-urlhelper-generateurl but, is it the best way to do it? How would I pass some helpful error message to the view. – Amila Sep 20 '13 at 10:00
  • sorry, the link should be http://stackoverflow.com/questions/13264496/asp-net-mvc-4-custom-authorize-attribute-with-permission-codes-without-roles – Amila Sep 20 '13 at 10:06