一、简介
今天讲一下 .NET Framework 程序中拦截 HTTP 请求,这主要用于记录 HTTP 信息,调试程序、分析程序性能等方面。这里贴出实现的核心代码,具体需要结合自己的业务。
二、实现代码
创建一个普通的 HTTPInterceptortHandler 类 ,继承 DelegatingHandler 类,并重写 SendAsync 方法
public class HTTPInterceptortHandler : DelegatingHandler
{
protected override Task 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(
(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());
}
}
到此这篇关于.NET Framework拦截HTTP请求的实现的文章就介绍到这了,更多相关.NET Framework拦截HTTP内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!
