【问题标题】:Intercept and log httpRequest and response within my .Net application在我的 .Net 应用程序中拦截并记录 httpRequest 和响应
【发布时间】:2016-10-26 08:39:11
【问题描述】:

我需要创建一个类,以便在应用程序中拦截 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("-------------------------------");
    }
}

【问题讨论】:

  • “网络追踪”是什么意思?如果您在<system.diagnostics> 中启用<switch name="System.Net" value="verbose"/>,那么您将同时获得请求和响应。关于格式:它将使用标准 .NET 机制进行记录,然后您可以编写自己的侦听器(如果您不喜欢标准的TextWriterTraceListener 格式)。当然,如果你想解释它们,你需要理解日志消息。
  • 我用了这个msdn.microsoft.com/en-us/library/a6sbz1dx(v=vs.110).aspx .. 所以如果我写自己的listner,我可以控制输出格式?!
  • @AdrianoRepetti 我可以使用代码而不是 web.config 来做所有事情吗?
  • 是的,you can。请注意,要更改 format,您可能需要 parse System.Net 类的诊断输出(它可能会随着时间而改变......)。如果您需要高级定制,这可能不是最简单的任务。
  • @AdrianoRepetti 我创建了一个从 TextWriterTraceListener 扩展的客户侦听器,但请求和响应作为字符串传递,我将不得不解析所有内容并删除我不需要的额外字符串..等等,是否有比字符串更安全的拦截请求和响应的方法。

标签: c# .net logging httprequest tracking


【解决方案1】:

我假设您使用的是 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>

您发出的每个请求,它都会写入收到的响应的 url 和字符集。

将以下行替换为您的日志记录说明:

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

例如:

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

您可以记录我在上面定义的 responseurl 变量的不同属性。

希望对你有帮助

【讨论】:

  • 我需要创建一个 Helper 类,它可以在任何 .Net 应用程序调用 Web 服务(Web、Windows、Console ..任何东西)中使用
猜你喜欢
  • 2018-04-19
  • 1970-01-01
  • 2018-08-28
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多