新一个WebApi项目(Net Core 2.1)
public class InputOutputAlterMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public InputOutputAlterMiddleware (RequestDelegate next, ILoggerFactory loggerFactory )
{
_next = next;
_logger = loggerFactory.CreateLogger<InputOutputAlterMiddleware>();
}
public async Task InvokeAsync (HttpContext context )
{
var method = context.Request.Method;
if (method.Equals("POST" ))
{
var requestMessage = context.Request.Form["RequestMessage" ];
_logger.LogInformation("requestMessage:" + requestMessage);
var alterValue =$"{requestMessage} 被我修改啦!" ;
var dic = new Dictionary<string , StringValues>
{
{ "value" , new StringValues(alterValue) }
};
context.Request.Form = new FormCollection(dic);
using (var ms = new MemoryStream())
{
var orgBodyStream = context.Response.Body;
context.Response.Body = ms;
context.Response.ContentType = "multipart/form-data" ;
await _next(context);
using (var sr = new StreamReader(ms))
{
ms.Seek(0 , SeekOrigin.Begin);
var responseJsonResult = sr.ReadToEnd();
ms.Seek(0 , SeekOrigin.Begin);
var alterResult = $"没事返回值【{responseJsonResult} 】被我改过来啦!" ;
context.Response.Body = orgBodyStream;
await context.Response.WriteAsync(alterResult, Encoding.UTF8);
}
}
}
else
{
await _next(context);
}
}
}
public static class InputOutputAlterMiddlewareExtensions
{
public static IApplicationBuilder UseInputOutputAlter (
this IApplicationBuilder builder)
{
return builder.UseMiddleware<InputOutputAlterMiddleware>();
}
}
public void Configure (IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseInputOutputAlter();
app.UseMvc();
}
启动程序 用postman测试,注意Values控制器中的Post的FromBody特性修改成FromForm(只可意会,不可言传)
[HttpPost]
public async Task Post ([FromForm] string value)
{
await HttpContext.Response.WriteAsync("随便写了 反正你会改的!" );
}
代码github地址
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了