首页 > Web开发 > 详细

.net core 3.1 中间件或过滤器中读取post请求body的方法

时间:2021-05-20 15:26:35      阅读:26      评论:0      收藏:0      [点我收藏+]
//Get请求 ParseQueryString  转为 NameValueCollection 
NameValueCollection form = HttpUtility.ParseQueryString(context.HttpContext.Request.QueryString.ToString());

string data = string.Empty;
switch (method)
{
case "POST":
request.Body.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(request.Body, Encoding.UTF8))
{
data = reader.ReadToEnd();
}
break;
case "GET":
//第一步:取出所有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);

 原文:https://www.cnblogs.com/shenghuotaiai/p/12296801.html

.net core 3.1 中间件或过滤器中读取post请求body的方法

原文:https://www.cnblogs.com/johnblogs/p/14789436.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!