Follow by Email

Friday, December 5, 2014

Implementing Asp.net Custom MVC filters [Part 2]

hi in this post i will show an another way implementing custom asp.net mvc filters.
Now i will create separate class for every filter types which will inherit attributes according to type and then we will implement that inherited methods.
here we will use the name of filter class and add it on the top of action method or we can also add it to the whole controller.
Code :
1
Controller :
[CustomAuthorization]
public class MainController : Controller
{
//
// GET: /Main/
[CustomAction]
[CustomExceptionFilter]
public ActionResult Index()
{
int i = Convert.ToInt32(“1″) / Convert.ToInt32(“0″);
ViewBag.message = “hello world”;
return View();
}
}
class CustomAuthorization : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
filterContext.Controller.ViewBag.AuthorizationMsg = “From OnAuthorization method”;
}
}
class CustomAction : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.ViewBag.ActionExecutingMsg = “From OnActionExecuting method”;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
filterContext.Controller.ViewBag.ActionExecutedMsg = “From OnActionExecuted method”;
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewBag.ResultExecutingMsg = “From OnResultExecuting method”;
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.Controller.ViewBag.ResultExecutedMsg = “From OnResultExecuted method”;
}
}
public class CustomExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult
{
ViewName = “error”,
};
}
}
View:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.message
<br />
@ViewBag.AuthorizationMsg
<br />
@ViewBag.ActionExecutingMsg
<br />
@ViewBag.ActionExecutedMsg
<br />
@ViewBag.ResultExecutingMsg
<br />
@ViewBag.ResultExecutedMsg
<br />
@ViewBag.ExceptionMsg
</div>
</body>
</html>

I’m adding one more view named error.cshtml , to which we will redirect when any exception occurs.
2



Output:
1. Without Exception
1
2. With Exception
2