• .netcore3.1 多次获取请求body报 System.ObjectDisposedException: Cannot access a disposed object. Object name: 'FileBufferingReadStream'.


      开发中遇到 Cannot access a disposed object错误,大多数是多次读取请求Body流造成的,需要换一种获取请求Body流方法,不能使用StreamRreader方式,使用Body.CopyTo(ms)方法

      •  配置可以同步请求读取流数据
     public void ConfigureServices(IServiceCollection services)
            {
      //配置可以同步请求读取流数据
                services.Configure<KestrelServerOptions>(x => x.AllowSynchronousIO = true)
                    .Configure<IISServerOptions>(x => x.AllowSynchronousIO = true);
      • 在Startup配置中添加EnableBuffering

      

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
    
              app.Use(next => context =>
                {
                    context.Request.EnableBuffering();
                    return next(context);
                });    
      • 在过滤器中,获取Post请求Body的Context使用下面方式获取     
       public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
            {
                 context.HttpContext.Request.EnableBuffering();
                        context.HttpContext.Request.Body.Position = 0;
                        string bodyStr = string.Empty;
                        //using (var reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8))
                        //{
                        // var bodyRead = reader.ReadToEndAsync();
                        // bodyStr = bodyRead.Result;  //把body赋值给bodyStr
                        // needKey = JsonConvert.DeserializeAnonymousType
                //(bodyRead.Result, new Dictionary<string, object>())[dependencySource].ToString();
    //} using (var ms = new MemoryStream()) { context.HttpContext.Request.Body.CopyTo(ms); var b = ms.ToArray(); bodyStr = Encoding.UTF8.GetString(b); //把body赋值给bodyStr var dicObj= JsonConvert.DeserializeAnonymousType(bodyStr, new Dictionary<string, object>()); }



  • 相关阅读:
    Linux常用命令3
    清空指定表的所有记录数据。
    向已经创建好的表添加和删除指定的列族或列。
    在终端打印出指定表的所有记录数据。
    列出HBASE所有表的相关信息,如表名、创建时间等。
    我在校园自动签到系统
    charles配置
    计算机网络第7版 PDF+ 计算机网络释疑与习题解答第7版 PDF 计算机网络 课后答案
    在HDFS中将文件从源路径移动到目的路径。
    删除HDFS中指定的文件。
  • 原文地址:https://www.cnblogs.com/personblog/p/13259732.html
Copyright © 2020-2023  润新知