拦截并记录我的.Net应用程序中的httpRequest和响应

时间:2016-10-26 08:39:11

标签: c# .net logging httprequest tracking

我需要创建一个类,它允许在应用程序中拦截httpRequest(因此不需要代理)并记录请求和响应详细信息。 创建HttpRequest可以使用任何方式创建(HttpClient,HttpWebRequest,Helper库,如RestSharp ......任何东西),我希望创建动态类包含在HttpRequest初始化时触发的事件。

我已经使用网络跟踪,但我可以记录的只是字符串,那么是否有更安全的方法来拦截请求和响应对象而不是解析字符串

public class DebugTraceListener : System.Diagnostics.TextWriterTraceListener
{
    public override void Write(string message)
    {
        using (StreamWriter w = File.AppendText("D:\\Log\\log2.txt"))
        {
            Log(message, w);
        }
    }

    public override void WriteLine(string message)
    {
        using (StreamWriter w = File.AppendText("D:\\Log\\log2.txt"))
        {
            Log(message, w);
        }
    }

    public static void Log(string logMessage, TextWriter w)
    {
        w.WriteLine("  :{0}", logMessage);
        w.WriteLine("-------------------------------");
    }
}

1 个答案:

答案 0 :(得分:0)

我假设您使用的是asp.net webforms或asp.net mvc。您需要创建一个扩展类HttpApplication的类并实现接口IHttpModule

我创建了以下模块:

using System.Web;


namespace WebApplication1.App_Start
{
using System;

public class RequestHandler : HttpApplication,IHttpModule
{
    /// <summary>
    /// Initializes a module and prepares it to handle requests.
    /// </summary>
    /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application </param>
    public void Init(HttpApplication context)
    {

        context.BeginRequest += context_BeginRequest;
        context.EndRequest += context_RequestCompleted;
    }

    void context_RequestCompleted(object sender, EventArgs e)
    {
        var application = (HttpApplication)sender;
        var context = application.Context;

        var response = context.Response;
        context.Response.Write(response.Charset);
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        var application = (HttpApplication)sender;
        var context = application.Context;

        var url = context.Request.Url;
        context.Response.Write(url.AbsoluteUri);
    }

    /// <summary>
    /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
    /// </summary>
    public void Dispose()
    {
        throw new NotImplementedException();
    }



}
}

接下来,通过在下面添加以下行来注册web.config中的HttpModule:

<system.webServer>
<modules>
  <add name="Handler" type="WebApplication1.App_Start.RequestHandler"/>
  <remove name="FormsAuthenticationModule" />
</modules>
</system.webServer>

您提出的每个请求都会写入收到的回复的网址和字符集。

通过日志记录说明替换以下行:

context.Response.Write(url.AbsoluteUri);
context.Response.Write(response.Charset);

例如:

Logger.Log(url.AbsoluteUri) //in context_BeginRequest
Logger.Log(response.ContentType) //in context_RequestCompleted

您可以记录我在上面定义的响应网址变量的不同属性。

希望有所帮助