当前位置: 代码网 > it编程>编程语言>Asp.net > .NET Framework拦截HTTP请求的实现

.NET Framework拦截HTTP请求的实现

2024年05月15日 Asp.net 我要评论
一、简介今天讲一下 .net framework 程序中拦截 http 请求,这主要用于记录 http 信息,调试程序、分析程序性能等方面。这里贴出实现的核心代码,具体需要结合自己的业务。二、实现代码

一、简介

今天讲一下 .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内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com