在一次数据接口对接时,需要接收其他服务器POST到我正在开发的项目中,接口接收的数据始终为空,后来找到原因是因为 mvc中,Request.InputStream的指针初始位置已经在末尾了,所以当我再次读取时,数据始终为空,这时,只需要将读取数据的指针位置重置即可。
关键代码:
//重置指针位置(这句代码很关键)
System.Web.HttpContext.Current.Request.InputStream.Position = 0;
调试结果:
完整代码:
/// <summary>
/// 获取数据【测试】
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetData(string key)
{
var data = "没得数据呢";
//读取当前数据流指针位置
var position = System.Web.HttpContext.Current.Request.InputStream.Position;
//重置指针位置(这句代码很关键)
System.Web.HttpContext.Current.Request.InputStream.Position = 0;
using (Stream stream = System.Web.HttpContext.Current.Request.InputStream)
{
byte[] postBytes = new byte[stream.Length];
stream.Read(postBytes, 0, (int)stream.Length);
data = Encoding.UTF8.GetString(postBytes);
}
return data;
}