惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Latest
Security Latest
Recorded Future
Recorded Future
人人都是产品经理
人人都是产品经理
S
SegmentFault 最新的问题
Hacker News - Newest:
Hacker News - Newest: "LLM"
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
P
Privacy & Cybersecurity Law Blog
WordPress大学
WordPress大学
Know Your Adversary
Know Your Adversary
Spread Privacy
Spread Privacy
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Tor Project blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
阮一峰的网络日志
阮一峰的网络日志
V
Visual Studio Blog
T
Threatpost
T
Tenable Blog
有赞技术团队
有赞技术团队
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
C
Cisco Blogs
H
Heimdal Security Blog
Attack and Defense Labs
Attack and Defense Labs
A
About on SuperTechFans
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
T
Threat Research - Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
I
Intezer
V
V2EX
Cyberwarzone
Cyberwarzone
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
B
Blog RSS Feed
V
Vulnerabilities – Threatpost
N
Netflix TechBlog - Medium
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
PCI Perspectives
PCI Perspectives
P
Privacy International News Feed
D
Docker

博客园 - BloggerSb

Swagger 文档设置api版本 .Net Core Routing Demo .net Core读取配置比较 简化版DbExecutor,将DataTable映射到T属性(支持Dapper风格的匿名参数)。(编程题) 大文件单词统计 (编程题) ASP.NET Core CRUD API 创建 UserController,实现 Get, Post, Put, Delete 方法,使用 EF Core 访问数据库。 (编程题) 设计模式落地:Repository + UnitOfWork + CQRS 完整实现 (编程题) 给定百万级订单表,实现高效分页 + 动态条件查询 + 导出 Excel(避免内存爆炸) (编程题) 实现一个带 CorrelationId、请求日志、异常统一处理的中间件链 (编程题) 异步限流器实现(编程题) .net面试题目 (问答题) 面试高频简答题 Aspose最新Slides破解 HttpContext.User.Identity.IsAuthenticated 为false 关于Cannot resolve scoped service from root provider解决方案 MongoDB用户权限管理,设置密码并连接 mongodb连接字符串 mongodb 使用 MongoDB Compass 创建账号,角色 安装mongodb bootstrap popover 设置悬浮框宽度 div contenteditable="true" 添加placehoder效果 光标自动定位到起始位置contenteditable="true" ,v-html绑定内容,div可编辑时,光标移到最前面
编程题,记录所有接口的执行耗时
BloggerSb · 2026-04-17 · via 博客园 - BloggerSb

编写一个ASP.NET Core中间件,记录所有接口的执行耗时,当耗时超过500ms时,将请求报文(Header、Body)记录到异常日志中,支持依赖注入日志服务。

考察点:HttpContext操作、请求体回滚(EnableBuffering)、依赖注入(ILogger)、日志分级、资源释放。

public class RequestDurationMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestDurationMiddleware> _logger;

    public RequestDurationMiddleware(RequestDelegate next, ILogger<RequestDurationMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 记录请求开始时间
        var startTime = DateTime.Now;

        // 启用请求体回滚(默认请求体只能读取一次)
        context.Request.EnableBuffering();

        try
        {
            // 执行下一个中间件(接口逻辑)
            await _next(context);
        }
        finally
        {
            // 计算执行耗时
            var duration = DateTime.Now - startTime;
            var path = context.Request.Path;
            var method = context.Request.Method;

            // 记录耗时日志
            _logger.LogInformation("接口 {Method} {Path} 执行耗时:{Duration}ms", 
                method, path, duration.TotalMilliseconds.ToString("F2"));

            // 耗时超过500ms,记录请求报文
            if (duration.TotalMilliseconds > 500)
            {
                // 读取请求头
                var headers = context.Request.Headers.Select(h => $"{h.Key}: {string.Join(",", h.Value)}");
                var headerStr = string.Join(Environment.NewLine, headers);

                // 读取请求体
                string bodyStr = string.Empty;
                if (context.Request.ContentLength > 0)
                {
                    // 重置请求体位置,避免后续中间件无法读取
                    context.Request.Body.Position = 0;
                    using var reader = new StreamReader(context.Request.Body);
                    bodyStr = await reader.ReadToEndAsync();
                    // 重置位置,供后续使用
                    context.Request.Body.Position = 0;
                }

                // 记录详细日志
                _logger.LogWarning("接口 {Method} {Path} 耗时过长({Duration}ms),请求详情:{Environment.NewLine}请求头:{HeaderStr}{Environment.NewLine}请求体:{BodyStr}",
                    method, path, duration.TotalMilliseconds.ToString("F2"), headerStr, bodyStr);
            }
        }
    }
}

// 扩展方法
public static class RequestDurationMiddlewareExtensions
{
    public static IApplicationBuilder UseRequestDurationLogger(this IApplicationBuilder app)
    {
        return app.UseMiddleware<RequestDurationMiddleware>();
    }
}