当前位置:   article > 正文

.NET Framework拦截HTTP请求_net framework防止浏览器访问

net framework防止浏览器访问

一、简介

今天讲一下 .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;
            }
        );
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

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

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // 在 Application_Start 方法添加这一行
        GlobalConfiguration.Configuration.MessageHandlers.Add(new HTTPInterceptortHandler()); 
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/885578
推荐阅读
相关标签
  

闽ICP备14008679号