(精華)2020年7月1日 ASP.NET Core 使用Enablebuffering多次讀取body

愚公搬程式碼發表於2020-07-01
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    //允許body重用
    app.Use(next => context =>
    {
        context.Request.EnableBuffering();
        return next(context);
    })
}
[HttpPost]
public async Task<string> Post()
{
    //StreamReader sr = new StreamReader(Request.Body);
    //string data = await sr.ReadToEndAsync();

    string data = "";

    //Request.EnableBuffering();可以實現多次讀取Body
    Request.EnableBuffering();
    StreamReader sr = new StreamReader(Request.Body);
    data = await sr.ReadToEndAsync();
    logger.LogInformation("data=" + data);
    Request.Body.Seek(0, SeekOrigin.Begin);

    //再次讀取 依然可以成功讀到
    Request.EnableBuffering();
    StreamReader sr2 = new StreamReader(Request.Body);
    string data2 = await sr2.ReadToEndAsync();
    logger.LogInformation("data2=" + data2);
    Request.Body.Seek(0, SeekOrigin.Begin);
    

    string header = $"請求頭:\r\n";
    foreach (var item in Request.Headers)
    {
        header += $"{item.Key}:{item.Value}\r\n";
    }
    logger.LogInformation(header);

    var ip = Request.Headers["X-Forwarded-For"].FirstOrDefault();
    if (string.IsNullOrEmpty(ip))
    {
        //ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
        //ip = Request.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString();
        ip = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
    }
    logger.LogInformation("ip=" + ip);
}

相關文章