Debugging ASP.NET MVC Action Filters

I was recently lucky enough to find the root cause of the error in an ASP.NET MVC action. The error ended up in one of the action filters declared in the action. However, finding this error was mostly just luck, and took longer than was reasonable. In the future, how can I debug problems with ASP.NET MVC action filters?

In particular:

  • How do you know which filters are running for a particular query and in what order?
  • Can I go through these filters?
  • Is it possible at least to get some kind of hook to execute between each filter to help find the root cause (e.g. by tracking some state)?
  • Is there some event that I can hook up when the filter interrupts the request or throws an exception?

I tried using the VS.NET debugger; however, it will not enter filters in a useful way. If I pause execution before the request, the server waits for a debugger if needed, but when I then use Step in or step it just continues without stepping through any filters (only my code is off). Perhaps I could set a breakpoint if I knew ahead of time which filters were registered, but this is hardly practical because some filters are in third party code.

+3


source to share


1 answer


The following code will record the name of the controllers and actions in the sequence they call. I hope this helps someone else as it helped me a lot.

It will be great if you have a base controller and the rest of the controllers inherit from it, then the following code will let you know all the controllers and actions that are called for any request.



#if DEBUG 
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                 string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                 string action = filterContext.ActionDescriptor.ActionName;

                 Debug.WriteLine("Controller-" + controller + ", Action-" + action);
            }
#endif

      

PS - If you need more information like action processing times or any kind of pluggable system, use Glimpse . It only takes a few minutes to run. This is a great tool. On the other hand, glimpse timings are not accurate as there is some Glimpse overhead included as well.

+3


source







All Articles