I am trying out the following scenario in ASP.NET MVC. I want to built a simple MVC application where I want to create a custom IAuthorizationFilter which should only execute an SQL Statement to check if user exists. If user exists then go on otherwise redirect to a different view.
I created a new class for the custom filter:
public class CustomAuthorizationAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.Controller.ViewBag.AutherizationMessage = "Custom Authorization: Message from OnAuthorization method.";
}
}
In the action where I wanted to check for the user I added the filter:
[CustomAuthorizationAttribute]
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
In the view, I added the output value:
<div>
@ViewBag.AutherizationMessage
</div>
In general when I execute the solution and execute the action I receive the message on the website as expected.
But know I a real world scenario, how and where to implement the check and how to redirect on Not Authorized?
1.Create your custom Authorize attribute as mentioned below: 2.Create an action in your controller handling invalid user (like Restricted action in home Controller in below example , this action simply return a view)
Now user this custom Authorize attribute in your action wherever you need. hope this help you :)