免费资源网 – https://freexyz.cn/

目录
  • 一、简介
  • 二、实现代码

一、简介

今天讲一下 .NET Framework 程序中拦截 HTTP 请求,这主要用于记录 HTTP 信息,调试程序、分析程序性能等方面。这里贴出实现的核心代码,具体需要结合自己的业务。

二、实现代码

创建一个普通的 HTTPInterceptortHandler 类 ,继承 DelegatingHandler 类,并重写 SendAsync 方法

public class HTTPInterceptortHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // 根据需求调试,获取更多数据
        string requestIP = HttpContext.Current?.Request?.UserHostAddress;
        string requestContent = request.Content?.ReadAsStringAsync()?.Result;
        string requestUri = request.RequestUri.AbsoluteUri;

        return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(
            (task) =>
            {
                string responseContent = task.Result.Content.ReadAsStringAsync().Result;
                string responseCode = task.Result.StatusCode.ToString();

                // 记录日志、加工一下结果等都可以在这里处理

                return task.Result;
            }
        );
    }
}

在 Global.asax 的 Application_Start 方法中注册写好的 HTTPInterceptortHandler 类

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // 在 Application_Start 方法添加这一行
        GlobalConfiguration.Configuration.MessageHandlers.Add(new HTTPInterceptortHandler()); 
    }
}

免费资源网 – https://freexyz.cn/

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。