本博文參考了: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) { } });
