Topic:   Custom filter - action filter
Oct 06, 2020 17:48 2 Replies 953 Views HIMANSHU

i want to create action filter a cutom filter . how to create ?.

Prev Next
Topic Replies (2)
  1. 1
    idnkx user


    To implement action filters, you need to create custom action filters. Now, you are going to create a Custom Action Filter which implements the pre-processing and post-processing logic. It will inherit from ActionFilterAttribute class and also implement IActionFilter interface.

    idnkx user


    To create a custom action filter, we need to perform the following tasks:

    Create a class
    Inherit it from ActionFilterAttribute class
    Override at least one of the following methods:
    OnActionExecuting – This method is called before a controller action is executed.
    OnActionExecuted – This method is called after a controller action is executed.
    OnResultExecuting – This method is called before a controller action result is executed.
    OnResultExecuted – This method is called after a controller action result is executed.
    Let us create a custom action filter which will perform two tasks, in the most simplistic way. Of course, you can write more sophisticated code inside the custom action filter, but we are going to create a custom filter with the name MyFirstCustomFilter, which will perform the following two tasks:

    Set some data value in global ViewBag.
    Log the incoming request to the controller action method.
    The filter can be created as shown in the listing below:

    using System;
    using System.Diagnostics;
    using System.Web.Mvc;

    namespace WebApplication1
    public class MyFirstCustomFilter : ActionFilterAttribute
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    //You may fetch data from database here
    filterContext.Controller.ViewBag.GreetMesssage = "Hello Foo";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    var controllerName = filterContext.RouteData.Values["controller"];
    var actionName = filterContext.RouteData.Values["action"];
    var message = String.Format("{0} controller:{1} action:{2}", "onactionexecuting", controllerName, actionName);
    Debug.WriteLine(message, "Action Filter Log");
    In the above listing, we are simply setting ViewBag property for the controllers being executed. The ViewBag property will be set before a controller action result is executed since we are overriding the OnResultExecuting method. Also, we are overriding OnActionExecuting to log the information about controller’s action method.

Leave a Reply
Guest User

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.

Let`s Connect