Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC Action Filter : What is the difference between OnActionExecuting and OnResultExecuting regarding usage

Tags:

I am looking for a comparison between OnActionExecuting and OnResultExecuting.

When should one work with OnActionExecuting, and when with OnResultExecuting?

like image 401
Thomas Avatar asked Mar 19 '16 08:03

Thomas


1 Answers

From Filtering in ASP.NET MVC:

  • Action filters. These implement IActionFilter and wrap the action method execution. The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecuted. OnActionExecuting runs before the action method. OnActionExecuted runs after the action method and can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.

  • Result filters. These implement IResultFilter and wrap execution of the ActionResult object. IResultFilter declares two methods: OnResultExecuting and OnResultExecuted. OnResultExecuting runs before the ActionResult object is executed. OnResultExecuted runs after the result and can perform additional processing of the result, such as modifying the HTTP response. The OutputCacheAttribute class is one example of a result filter.

In short, these are events from 2 different types of filters that execute at different times.

IActionFilter.OnActionExecuting executes before the action method does. IResultFilter.OnResultExecuting executes after the action method returns (i.e. calls return View()), but before the ActionResult executes.

In plain English: OnActionExecuting can be used to intervene before the business logic runs. OnResultExecuting can be used to intervene after the business logic runs and before the display logic runs.

like image 188
NightOwl888 Avatar answered Oct 13 '22 13:10

NightOwl888