IIS 7 Log Request Body

Viewed 35555

I need to log the request post payload for requests made to IIS. Is this possible to configure the logging of request post payloads with the existing logging and advanced logging modules within IIS 7.5 or can anybody direct me to any custom modules that will allow me to log the post payload.

3 Answers

Here is code of custom HTTP module we use to log HTTP POST request data.

using System;
using System.Web;

namespace MySolution.HttpModules
{
    public class HttpPOSTLogger : IHttpModule
    {

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        private void context_BeginRequest(object sender, EventArgs e)
        {
            if (sender != null && sender is HttpApplication)
            {
                var request = (sender as HttpApplication).Request;
                var response = (sender as HttpApplication).Response;

                if (request != null && response != null && request.HttpMethod.ToUpper() == "POST")
                {
                    var body = HttpUtility.UrlDecode(request.Form.ToString());
                    if (!string.IsNullOrWhiteSpace(body))
                        response.AppendToLog(body);
                }
            }
        }

    }
}

Do not forget to register it in web.config of you application.

Use system.WebServer section for IIS Integrated Model

<system.webServer>
    <modules>
      <add name="HttpPOSTLogger" type="MySolution.HttpModules.HttpPOSTLogger, MySolution.HttpModules" />
    </modules>
</system.webServer>

Use system.web section for IIS Classic Model

<system.web>
    <httpModules>
        <add name="HttpPOSTLogger" type="MySolution.HttpModules.HttpPOSTLogger, MySolution.HttpModules"/>
    </httpModules>
</system.web>

IIS log Before applying module:

::1, -, 10/31/2017, 10:53:20, W3SVC1, machine-name, ::1, 5, 681, 662, 200, 0, POST, /MySolution/MyService.svc/MyMethod, -,

IIS log After applying module:

::1, -, 10/31/2017, 10:53:20, W3SVC1, machine-name, ::1, 5, 681, 662, 200, 0, POST, /MySolution/MyService.svc/MyMethod, {"model":{"Platform":"Mobile","EntityID":"420003"}},

Full article:

https://www.codeproject.com/Tips/1213108/HttpModule-for-logging-HTTP-POST-data-in-IIS-Log

Related