中间件简介
ASP.NET Core 由很多中间件构成,实现了一个HTTP请求管道(pipeline)。
Request的Response的管道可以看成一个Push Stack 和 Pop Stack。
在Startup.cs的Configure方法中配置中间件。
实现一个中间件
- 构造函数RequestDelegate参数;
- 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>();
//......
运行
即可看到效果