开发手册 欢迎您!
软件开发者资料库

ASP.NET Core(C#) 在请求的响应内容前后添加自定义Html输出的方法及示例代码

本文主要介绍ASP.NET Core(C#)中,使用中间件或自定义实现IOutputFormatter的方式,在请响应时输出内容前后增加自定义Html方法,以及相关的示例代码。

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); }}