Search code examples
asp.net-mvc-3action-filter

HttpContext.Current vs ActionExecutingContext


If I am writing an ActionFilter like this

public override void OnActionExecuting(ActionExecutingContext filterContext)

within this method, I can also get access to current context via HttpContext.Current. I am just wondering what is the difference between these two contexts?


Solution

  • From an article on filters:

    When you implement the OnActionExecuted method, you’ll end up receiving an instance of type ResultExecutedContext. Besides letting you get access to the currentControllerContext, you’ll also get properties for

    • getting the ActionResult (property Result) responsible for generating the response returned to the client;

    • seeing if the processing was cancelled (which happens when, for instance, you set the Result property of the ActionExecuting context from within the OnActionExecuting method). You can get this info from the Canceled property;

    • getting a reference to an exception that might have been generated during the processing (as you might expect, this is available through the Exception property);

    • indicating that you’ve handled an exception (property ExceptionHandled).

    ... The ResultExecutingContext is a little different from the ActionExecutingContext we’ve talked about. If you build one of these filters, then you can cancel further processing by setting the Cancel property to true from within the OnResultExecuting method. Notice that when this happens, your view won’t be called and you end up not generating the HTML that is generally sent back to the client (I’m assuming a simple case, where you have a view that generates HTML. As we’ll see, you can also have a view that generates JSON…).