.Net MVC C# OnActionExecuting example

A quick demo of how to hook up the OnActionExecuting method in an custom ActionFilter.

1) Create an ActionFilter class

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;

namespace CsharpWebAPIDemo.ActionFilters
{
    /// <summary>
    /// Custom action filter class for logging request variables
    /// </summary>
    public class LogActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            LogRequestVars("OnActionExecuting", filterContext);
        }

        /// <summary>
        /// Logs the request vars.
        /// </summary>
        /// <param name="methodName">Name of the method.</param>
        /// <param name="values">The values.</param>
        private static void LogRequestVars(string methodName, ActionExecutingContext values)
        {
            // Get the request keys
            var keys = values.RequestContext.HttpContext.Request.Headers.AllKeys;

            // Get the request key value pairs
            var requestVars = keys.Select(key => new KeyValuePair<string, string>(key, values.RequestContext.HttpContext.Request.Headers.Get(key)));

            // Write to Debug log
            Debug.WriteLine("Method: {0}", methodName);

            foreach (var keyValuePair in requestVars)
            {
                Debug.WriteLine("{0} - {1}", keyValuePair.Key, keyValuePair.Value);
            }
        }
    }
}

2) Add the ActionFilter to you Controller class

using System.Web.Mvc;
using CsharpWebAPIDemo.ActionFilters;

namespace CsharpWebAPIDemo.Controllers
{
    public class HomeController : Controller
    {
        [LogActionFilter]
        public ActionResult Index()
        {
            return View();
        }
    }
}

The output is displayed in the output window of the debugger in Visual Studio.

Leave a Reply

Your email address will not be published. Required fields are marked *