一、简介
今天讲一下 .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()); } }
到此这篇关于.net framework拦截http请求的实现的文章就介绍到这了,更多相关.net framework拦截http内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论