1、使用中间件的方法
public class BeforeAfterMiddleware{ private readonly RequestDelegate _next; public BeforeAfterMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { using var actionResponse = new MemoryStream(); var httpResponse = context.Response.Body; context.Response.Body = actionResponse; await _next.Invoke(context); actionResponse.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(actionResponse); using var bufferReader = new StreamReader(actionResponse); string body = await bufferReader.ReadToEndAsync(); context.Response.Clear(); await context.Response.WriteAsync("wonhero:原始内容之前
"); await context.Response.WriteAsync(body); await context.Response.WriteAsync("wonhero:原始内容之后
"); context.Response.Body.Seek(0, SeekOrigin.Begin); await context.Response.Body.CopyToAsync(httpResponse); context.Request.Body = httpResponse; }}
使用方法:
app.UseMiddleware();
2、实现IOutputFormatter
在ConfigureServices()方法中添加代码,如下,
services.AddControllers(opt =>{ //默认 OutputFormatters : //HttpNoContentFormatter,StringOutputFormatter, //StreamOutputFormatter,SystemTextJsonOutputFormatter opt.OutputFormatters.Clear(); //opt.OutputFormatters.RemoveType(); //opt.OutputFormatters.RemoveType (); opt.OutputFormatters.Add(new AppendHtmlOutputFormatter());});
实现IOutputFormatter如下,
public class AppendHtmlOutputFormatter : IOutputFormatter{ public bool CanWriteResult(OutputFormatterCanWriteContext context) => true; public Task WriteAsync(OutputFormatterWriteContext context) { var json = System.Text.Json.JsonSerializer.Serialize(context.Object); var modified = "wonhero:原始内容之前
" + json + "wonhero:原始内容之后
"; return context.HttpContext.Response.WriteAsync(modified); }}