• Middleware In ASP.NET Core


    中间件简介

    ASP.NET Core 由很多中间件构成,实现了一个HTTP请求管道(pipeline)。

    Request的Response的管道可以看成一个Push Stack 和 Pop Stack。

    在Startup.cs的Configure方法中配置中间件。

    实现一个中间件

    1. 构造函数RequestDelegate参数;
    2. Invoke(HttpContext context)方法;
    using Microsoft.AspNetCore.Http;
    using System.Threading.Tasks;
    using System.Diagnostics;
    using System.IO;
    
    namespace WebAppWithIndividualUserAccounts
    {
        public class ResponseTime
        {
            RequestDelegate _next;
            public ResponseTime(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context)
            {
                var sw = new Stopwatch();
                sw.Start();
    
                await _next(context);
    
                var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");
                if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
                {
                    var body = context.Response.Body;
    
                    using (var streamWriter = new StreamWriter(body))
                    {
                        var txtHtml = $"<footer><div id='process'>Response Time {sw.ElapsedMilliseconds} milliseconds.</div></footer>";
    
                        streamWriter.Write(txtHtml);
                    }
                }
            }
        }
    }
    
    

    注册一个中间件

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                app.UseMiddleware<ResponseTime>();
                //......
    

    运行

    即可看到效果

  • 相关阅读:
    C# 利用 Geckofx60 实现下载
    C# 线程 线程池
    C# DateTime 与 String 格式转换
    C# WPF 获取程序路径
    C# 计时器 Timer 介绍
    获取远程图片并把它保存到本地
    php sql 过滤
    PHP如何生成伪静态
    用php获取客户端IP地址的方法
    php过滤危险html代码
  • 原文地址:https://www.cnblogs.com/pengzhen/p/5757054.html
Copyright © 2020-2023  润新知