Net Core 中间件实现修改Action的接收参数及返回值

时间:2021-07-05 04:42:20

新一个WebApi项目(Net Core 2.1)

新建InputOutputAlterMiddleware类,修改命名空间为Microsoft.AspNetCore.Builder(不修改也没关系,套路而已)
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;
//判断是POST提交过来的
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);
//得到Action的返回值
var responseJsonResult = sr.ReadToEnd();
ms.Seek(0, SeekOrigin.Begin);
//如下代码若不注释则会显示Action的返回值 这里做了注释 则清空Action传过来的值
// await ms.CopyToAsync(orgBodyStream);
var alterResult = $"没事返回值【{responseJsonResult}】被我改过来啦!"; context.Response.Body = orgBodyStream;
//显示修改后的数据
await context.Response.WriteAsync(alterResult, Encoding.UTF8); }
} }
else
{
await _next(context);
} }
}
新建InputOutputAlterMiddlewareExtensions类,修改命名空间Microsoft.AspNetCore.Builder
public static class InputOutputAlterMiddlewareExtensions
{
public static IApplicationBuilder UseInputOutputAlter(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<InputOutputAlterMiddleware>();
}
}
在Startup类Configure方法下 添加app.UseInputOutputAlter();
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseInputOutputAlter();
app.UseMvc();
}
启动程序 用postman测试,注意Values控制器中的Post的FromBody特性修改成FromForm(只可意会,不可言传)
    // POST api/values
/// <summary>
/// 把FromBody修改成了FromForm 因为这里测试是用form提交的
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
[HttpPost]
public async Task Post([FromForm] string value)
{
await HttpContext.Response.WriteAsync("随便写了 反正你会改的!");
}

Net Core  中间件实现修改Action的接收参数及返回值

代码github地址