由于项目需要,对用户所有请求记录需要记录到数据库内,开始使用中间件方式可以读取,需要在Startup中设置同步读取:
ConfigureServices中添加允许同步读取Body代码:
services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
})
.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
Configure方法中,app.UseEndpoints之前添加如下代码
app.Use((context, next) =>
{
context.Request.EnableBuffering();
return next();
});
读取Post json数据:
var requestMethod = httpContext.Request.Method;
var requestURL = $"{httpContext.Request.Scheme}://{httpContext.Request.Host}{httpContext.Request.Path}";
var accessToken = string.Empty;
var requestBody = string.Empty;
if (requestMethod == "POST")
{
var request = httpContext.Request;
request.Body.Position = 0;
System.IO.StreamReader sr = new System.IO.StreamReader(request.Body);
string body = sr.ReadToEnd();
request.Body.Position = 0;
}
get请求直接 string body = httpContext.Request.QueryString.ToString(); 即可。
同样代码我拿到过滤器get请求没问题,但是Post Json方式总是报异常:
System.ObjectDisposedException: Cannot access a disposed object. Object name: 'FileBufferingReadStream'.
网上能查到的大部分方式都是如上配置,搞了两天终于查找到想要的数据,如下图:
最终要的数据就是通过红框内属性读取到就可以了,不需要在Request.Body中读取,这样就将请求参数读取到写入数据库了,如下图:
也可以获取到执行完成后获取返回值:
next.Invoke()执行完action之后 vResult对象就会包含返回值信息,直接按照自己逻辑读取即可,如下图:
这是整个执行完成后,写入数据库的请求记录。