MVC-Action Filters

Action Filters

 

 

Action filters will apply pre or post Processing logic to a controller action and it result. Action filters are the component we want to use to apply cross cutting logic to our application i.e. the logic that we must execute across multiple controller actions but we do not want to duplicate the logic inside of individual controller.


Name Description
OutputCache Cache the output of an Action method.
Authorize Restrict an action or controller to authorize user or role.
ValidateInput Turn on/off the request validation.
ValidateAntiForgeryToken Helps prevent cross site request forgeries.
HandleError Can specify a view to render in the event of an unhandled exception.
OutputCache: tells the runtime that it allows to cache the final output of the action and use the cache result to serve the future request.

   [OutputCache(Duration=10, VaryByParam="t1")]
Authorize: Authorize attribute allow us to ensure that user is login before action/controller allow to process the request.

[Authorize] // To access the Feedback Action Method User have to login.

public ActionResult Feedback()

{
return View();
}

[Authorize] // To access the FeedbackController User have to login.

public class FeedbackController : Controller
{
public ActionResult Feedback()
{
return View();
}
[HttpPost]
public ActionResult Feedback(Feedback f)
{
return View("FeedbackDisplay", f);
}
}

ValidateInput: To allow or disallow submission of tags and other potentially dangerous content.

[HttpPost()]

[ValidateInput(false)]

public ActionResult Index(FormCollection col)

{

ViewBag.Greetings1 = DateTime.Now;

return View();

}

ValidateAntiForgeryToken: If this attribute is provided then cross site submission will not be allowed.

[HttpPost(), ValidateAntiForgeryToken()]

public ActionResult Index(FormCollection col)

{
 return View();

}

In View Add the following:
@{
      Html.BeginForm();
@Html.AntiForgeryToken()

<input type="text" name="name" value="" /> 

<input type="submit" name="btnSubmit" value="Submit" /> 

Html.EndForm();
}

HandleError: attribute is used to display friendly error pages to the user when something goes wrong.

[HandleError]
public ActionResult Feedback()
{
throw new ApplicationException("Ooops!!!");
return View();
}


<system.web>

<customErrors mode="On"></customErrors>

</system.web>

If exception occurs then it will render the error page which is in the views folder and under the shared folder and is called Error.cshtml file.

Filter Types

ASP.NET MVC supports the following types of filters:

1. Authorization Filter:

- Class Implementing IAuthorizationFilter
-  Eg: AuthorizeAttribute and RequireHttpsAttribute
-Can override OnAuthorization method

2. Action Filter:

- Class Implementing IActionFilter
- Eg: ActionFilterAttribute – Used for writing Custom Attributes
- Can override OnActionExecuting and OnActionExecuted

3. Result Filter:

- Class Implementing IResultFilter
- Eg: OutputCacheAttribute.
- ActionFilterAttribute implements both IResultFilter and IActionFilter.
- Can override OnResultExecuting and OnResultExecuted

4. Exception Filter:

- Class Implementing IExceptionFilter
- Eg: HandleErrorAttribute
Note: Controller class Implements all of the above and we can override in it all the methods mentioned.
Building Custom Action Filters
An action filter is implemented as an attribute class that inherits from ActionFilterAttribute.
The base ActionFilterAttribute class has the following methods that you can override:-

 OnActionExecuting – This method is called before a controller action method is executed.

OnActionExecuted  – This method is called after a controller action method is executed.

OnResultExecuting – This method is called before the ActionResult instance that is returned by your action is invoked.

OnResultExecuted – This method is called after the ActionResult instance that is returned by your action is invoked.

The following example shows a simple action filter that logs trace messages:

public class LogAttribute :ActionFilterAttribute
          {
              public override void OnActionExecuting(ActionExecutingContext filterContext)
           {
                    //filterContext.Controller.ViewBag.DemoProperty = "From Action Filter";

          Trace("On Action Executing" , filterContext.RouteData);
             }
 public override void OnActionExecuted(ActionExecutedContext filterContext)
             { Trace("On Action Executed", filterContext.RouteData);
           
              }
 public override void OnResultExecuting(ResultExecutingContext filterContext)
       {
           //filterContext.HttpContext.Response.Write("Advertisement <hr>"); 

      Trace("On Result Executing", filterContext.RouteData);
           }
   public override void OnResultExecuted(ResultExecutedContext filterContext)
               {
              //filterContext.HttpContext.Response.Write("<hr>Advertisement");
                  Trace("On Result Executed", filterContext.RouteData);
                 }
         public void Trace (string methodName, RouteData routeData)

                  { string colName, actionName;
                    colName = routeData.Values["controller"].ToString();
                    actionName = routeData.Values["action"].ToString();
                    string str = string.Format("1 - Method Name={0}, Controller Name={1}, Action={2}", methodName, colName, actionName);
                     System.Diagnostics.Trace.WriteLine(str);
                      HttpContext.Current.Response.Write("<br/>" + str + "<br/>");
                     }
               }
Applying Custom Action filter to a controller or Action method:

[Log]
public ActionResult Index()
{
return View();
}
Note: We can also attach the attribute to Controller class

Global Registering Action filters:

In App_Start\FilterConfig.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new LogAttribute());
}




Learn Video based Training on ASP.NET MVC 5.2 

Comments

  1. your information is really awesome as well as it is very excellent and i got more interesting information from your blog. iOS App Development Company in Chennai

    ReplyDelete
  2. I think it's awesome someone is finally taking notice of our vet's and doing something to help them. I hope all goes well with these articles. More new information i will get after refer that post.
    Manufacturing ERP
    Oil and gas ERP
    ERP software companies
    Best ERP software
    ERP for the manufacturing industry

    ReplyDelete
  3. Nice post. It's very interesting post and useful information, you have done a great job.
    Thanks for sharing your knowledge. Keep sharing it like this.

    Vehicle tracking system
    Fleet management software

    ReplyDelete

Post a Comment