本文主要介绍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("<h1>cjavapy:原始内容之前</h1>");
        await context.Response.WriteAsync(body);
        await context.Response.WriteAsync("<h1>cjavapy:原始内容之后</h1>");

        context.Response.Body.Seek(0, SeekOrigin.Begin);
        await context.Response.Body.CopyToAsync(httpResponse);
        context.Request.Body = httpResponse;
    }
}

使用方法:

app.UseMiddleware<BeforeAfterMiddleware>();

2、实现IOutputFormatter

在ConfigureServices()方法中添加代码,如下,

services.AddControllers(opt =>
{
    //默认 OutputFormatters :
    //HttpNoContentFormatter,StringOutputFormatter, //StreamOutputFormatter,SystemTextJsonOutputFormatter
    opt.OutputFormatters.Clear();
    //opt.OutputFormatters.RemoveType<StringOutputFormatter>();
    //opt.OutputFormatters.RemoveType<SystemTextJsonOutputFormatter>();
    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 = "<h1>cjavapy:原始内容之前</h1>" + json + "<h1>cjavapy:原始内容之后</h1>";
        return context.HttpContext.Response.WriteAsync(modified);
    }
}

推荐文档