.net core 3.1 中间件或过滤器中读取post请求body方法/ ParseQueryString 转 NameValueCollection 类型

代码如下://Get请求 ParseQueryString  转为 NameValueCollection 
NameValueCollection form = HttpUtility.ParseQueryString(context.HttpContext.Request.QueryString.ToString());

//第一步:取出所有get参数
IDictionary<string, string> parameters = new Dictionary<string, string>();
for (int f = 0; f < form.Count; f++)
{
string key = form.Keys[f];
parameters.Add(key, form[key]);
}


// 第二步:把字典按Key的字母顺序排序
IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();


// 第三步:把所有参数名和参数值串在一起
StringBuilder query = new StringBuilder();
while (dem.MoveNext())
{
string key = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(key))
{
query.Append(key).Append(value);
}
}
data = query.ToString();
break;
default:


base.OnActionExecuting(context);
return;
}


post请求 body 获取数据为空 

解决方法  在站点启动时设置以插入中间件的方式启用EnableBuffering,以达到在全局多次读取的目的。

在 Startup 文件  Configure 中 加入  代码如下: 进行注册

 app.Use(next => context =>
      {
            context.Request.EnableBuffering();
            return next(context);
      });

此外,3.0中默认禁用了AllowSynchronousIO,同步读取body的方式需要ConfigureServices中配置允许同步读取IO流,否则可能会抛出异常 Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.
根据使用的托管的服务进行配置或直接使用异步读取方式。

services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
                .Configure<IISServerOptions>(x=>x.AllowSynchronousIO = true);