1.中间件:
using Microsoft.AspNetCore.Mvc;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseMiddleware<ReplaceMiddleware>();
app.MapControllers();
app.Run();
public class HomeController : Controller
{
[HttpGet("/")]
public IActionResult Index() => Content("XXX%%%%%%%%%%%%%%");
}
public class ReplaceMiddleware
{
private readonly RequestDelegate _next;
public ReplaceMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
string content;
var originalBody = context.Response.Body;
using (var memStream = new MemoryStream())
{
context.Response.Body = memStream;
await _next(context);
memStream.Position = 0;
string responseBody = await new StreamReader(memStream).ReadToEndAsync();
content = responseBody.Replace("XXX", "YYY");
context.Response.Body = originalBody;
await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(content));
}
}
}
2.ResultFilter:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
//app.UseMiddleware<ReplaceMiddleware>();
app.MapControllers();
app.Run();
public class HomeController : Controller
{
[HttpGet("/")]
[ReplaceFilter]
public IActionResult Index() => Content("XXX%%%%%%%%%%%%%%");
}
public class ReplaceFilterAttribute : ResultFilterAttribute
{
public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
string content;
var originalBody = context.HttpContext.Response.Body;
using (var memStream = new MemoryStream())
{
context.HttpContext.Response.Body = memStream;
await base.OnResultExecutionAsync(context, next);
memStream.Position = 0;
string responseBody = await new StreamReader(memStream).ReadToEndAsync();
content = responseBody.Replace("XXX", "YYY");
context.HttpContext.Response.Body = originalBody;
await context.HttpContext.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(content));
}
}
}
3.ActionFilter:
public class ReplaceFilterAttribute : ActionFilterAttribute
{
public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
{
string content;
var originalBody = context.HttpContext.Response.Body;
using (var memStream = new MemoryStream())
{
context.HttpContext.Response.Body = memStream;
await base.OnResultExecutionAsync(context, next);
memStream.Position = 0;
string responseBody = await new StreamReader(memStream).ReadToEndAsync();
content = responseBody.Replace("XXX", "YYY");
context.HttpContext.Response.Body = originalBody;
await context.HttpContext.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(content));
}
}
}