Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I log all query parameters in an action filter?

I am implementing a logger that should capture details through an action filter for the purposes of user activity recording and fault finding.

   public interface ISessionLogger
    {
        void LogUserActionSummary(int sessionId, string userActionType);    
        void LogUserActionDetail(int session, string userActionType, DateTime userActionStartedUtc, long actionDurationInMilliseconds, string queryParams, string referredFrom);
    }

I would like queryParams to capture all keys and values from the form collection, route values, action params, json calls and the querystring, which sounds like I would need

filterContext.Controller.ValueProvider

but it doesn't seem possible to loop through this. So in my FilterAttribute I have

public void OnActionExecuting(ActionExecutingContext filterContext)
{
    var paramList = new List<string>();
    if(filterContext.ActionParameters != null)
    {
        paramList.AddRange(filterContext.ActionParameters.Select(param => String.Format("{0}:{1}", param.Key, param.Value.ToString())));
    }
    if(filterContext.Controller.ValueProvider != null)
    {
        //loop through the valueprovider and save the key value pairs to paramList
    }

    _queryParams = string.Join(",", paramList);
}

Is there another way to achieve this within the OnActionExecuting method of an action filter?

like image 457
friedX Avatar asked Nov 15 '25 11:11

friedX


1 Answers

Why don't you simply log the entire Request body? This way you will have everything you need to reconstruct the user request.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var stream = filterContext.HttpContext.Request.InputStream;
    var data = new byte[stream.Length];
    stream.Read(data, 0, data.Length);
    Log(Encoding.UTF8.GetString(data));
}

As an alternative you could try logging all filterContext.HttpContext.Request.Params values as well as filterContext.RouteData values:

like image 130
Darin Dimitrov Avatar answered Nov 18 '25 19:11

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!