ASP.NET Core 5.0 中读取Request中Body信息

时间:2022-11-25 21:44:14

ASP.NET Core 5.0 中读取Request中Body信息

记录一下如何读取Request中Body信息

public class ValuesController : ControllerBase
{
[HttpPost]
[Route("Data")]
public async Task<string> RequestData()
{
string body; //获取body
Request.EnableBuffering();//可以实现多次读取Body
StreamReader sr = new StreamReader(Request.Body);
body = await sr.ReadToEndAsync();
Request.Body.Seek(0, SeekOrigin.Begin); //获取请求头
string header = $"请求头:";
foreach (var item in Request.Headers)
{
header += $"{item.Key}:{item.Value}";
} //获取请求ip
var ip = Request.Headers["X-Forwarded-For"].FirstOrDefault();
if (string.IsNullOrEmpty(ip))
{
ip = Request.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
}
//返回body信息
return body;
}
}

postman测试

ASP.NET Core 5.0 中读取Request中Body信息