本博文参考了:https://blog.csdn.net/a123_z/article/details/94011395
背景:最近公司做一个项目,需要对传输的数据进行RSA加密,明文就是JSON字符串,于是我们考虑使用中间件来处理加解密问题。
这里只模拟在中间件里面将Body数据重新赋值的方法。
控制器代码如下:

[HttpPost]
public IActionResult Save([FromBody]Student student)
{
    return Json(student);
}

中间件代码如下:

app.Use(async (context, next) =>
{
    try
    {
        using (var newRequest = new MemoryStream())
        {
            //替换request流
            context.Request.Body = newRequest;
            using (var writer = new StreamWriter(newRequest))
            {
                string content = "{\"Id\":\"1\",\"Name\":\"李四\"}";
                await writer.WriteAsync(content);//重新指定请求的数据
                await writer.FlushAsync();
                newRequest.Position = 0;
                context.Request.Headers["Content-Length"] = Encoding.UTF8.GetBytes(content).Length + "";
                await next();
            }
        }
    }
    catch (Exception ex)
    {

    }
});

 

相关文章:

  • 2021-08-23
  • 2021-05-29
  • 2023-02-15
  • 2020-06-04
  • 2021-06-27
  • 2022-03-06
  • 2019-06-15
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-15
  • 2021-07-24
  • 2021-12-05
  • 2022-12-23
  • 2022-03-06
  • 2021-08-22
相关资源
相似解决方案