赞
踩
今天讲一下 .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());
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。