ActionFilter in ASP.NET MVC - OnResultExecuting
Continuing my series on ASP.NET MVC ActionFilters, this time it's about the OnResultExecuting method (which runs before the result of the controller (e.g. ActionResult, ViewResult, etc) is run.
Since this filter runs after the action itself has completed, you won't be able to access any information about the action (except Route Data). The ResultExecutingContext has the basic context information that you've seen in the other contexts (HttpContext, Controller, RouteData), but it also has a "Cancel" bool property. If you set this property to true, the Result will not be executed (e.g. if it's a ViewResult, the View will not be returned to the browser; if it's a Redirect result, redirect headers will not be returned to the browser, etc). What you'll get by default is just a blank response with status code 200.
So why 'cancel' a result? You could substitute a cached view or replace it with some other response by directly manipulating the HttpContext. If the action returned a ViewResult, JsonResult, etc, you can still access the model passed to that result, to perform some logic or manipulate its properties.
As before, I created a kitchen sink view of ResultExecutingContext just for reference. I decided to put it in the ViewBag this time:
And here's a screenshot of the results in my browser:
One more to go in this series. As always, if there's something that you want more information or details on, feel free to leave a comment or send a contact form to me, and I'll be glad to help out in any way I can.