Question

There are a lot of questions about accessing the HttpRequest on stackoverflow already, but I have not been able to find one that I can use yet. If somebody could point me to an answer I would be grateful.

My problem is that I want to modify an existing application in the simplest way possible in order to add in full request logging. I'm aware there this can be done with Http modules and IIS logging or using Log4net etc etc. But I don't want to use any of these techniques because the application is unpredictable so I need a solution that does not require any configuration changes at all.

I have added OnActionExecuted to a base controller.

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    // todo: log request from filter context ....
    base.OnActionExecuted(filterContext);
}

In the "todo" part above I wish to read the raw http request and save it to a database file. Logging to a database is simple enough but what is the best way to serialize or otherwise convert the http request as a string?

Thank you

Was it helpful?

Solution

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    var request = filterContext.HttpContext.Request;
    var inputStream = request.InputStream;
    inputStream.Position = 0;
    using (var reader = new StreamReader(inputStream))
    {
        string headers = request.Headers.ToString();
        string body = reader.ReadToEnd();
        string rawRequest = string.Format(
            "{0}{1}{1}{2}", headers, Environment.NewLine, body
        );
        // TODO: Log the rawRequest to your database
    }
}

Oh and if you start doing that, I hope you have already planned the budget you will need for purchasing additional storage on your servers. Coz if you start logging the entire raw request on each request you're gonna need storage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top