How can I log all query parameters in an action fi

2019-05-10 19:25发布

问题:

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?

回答1:

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: