Reputation: 3816
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?
Upvotes: 1
Views: 3989
Reputation: 16723
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);
Upvotes: 1