.net core中間件修改請求的數據


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

    }
});

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM