【问题标题】:When trying to upload file, FileBufferingReadStream.ThrowIfDisposed() error occurr尝试上传文件时,发生 FileBufferingReadStream.ThrowIfDisposed() 错误
【发布时间】:2018-10-07 20:05:35
【问题描述】:

我收到一个带有Microsoft.AspNetCore.Http.IFormFile 输入控制器的图像文件。

我将此文件上传到 Azure Blob。

在此之前,我采取如下流程

控制器

[HttpPost]
public async void ActionMethod(IFormFile img)
{

    // some process        

    using(MemoryStream stream = new MemoryStream())
    {
        // (1)
        img.CopyTo(stream); // (2)
        stream.Seek(0, SeekOrigin.Begin);
        // call await cloud block blob.UploadFromStreamAsync(stream);
    }

    // some process
}

当通过using 时,流是

CanRead:    true
CanSeek:    true
CanTimeout: false
CanWrite:   true
Capacity:   0
Length:     0
Position:   0
ReadTimeout:  'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
WriteTimeout: 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'

(2)之后出现以下错误

System.ObjectDisposedException occurred
  HResult=0x80131622
  Message=Cannot access a disposed object
  ObjectName: 'FileBufferingReadStream'
  Source=Microsoft.AspNetCore.WebUtilities
  StackTrace:
    at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.ThrowIfDisposed()
    at Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.set_Position(Int64 value)
    at Microsoft.AspNetCore.Http.Internal.ReferenceReadStream..ctor(Stream inner, Int64 offset, Int64 length)
   at Microsoft.AspNetCore.Http.Internal.FormFile.OpenReadStream()
   at Microsoft.AspNetCore.Http.Internal.FormFile.CopyTo(Stream target)
   at AzureStorageManager.AzureStorageFileModules.<UploadFileAsync>d__11.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

真正的问题是上述代码在某些情况下运行良好,但在某些情况下却不行(我无法理解这种情况。file 每次都相同)。

请帮帮我……

【问题讨论】:

标签: c# asp.net-core azure-storage azure-blob-storage


【解决方案1】:

我花了一天时间来解决这个问题,上传这个问题后,我找到了解决方案。造成此问题的问题是 Action 方法的返回类型。如果返回类型不是Task&lt;T&gt;,则会发生错误。所以我修复了我的动作方法,比如

[HttpPost]
public async Task<int> ActionMethod(IFormFile img)
{
     // same

     return resultValue;
}

之后,错误不会出现。 其实我也不知道为什么。因此,如果您知道,请告诉我并分享您的知识。谢谢。

【讨论】:

  • Async void 在后台运行您的方法,因此您的请求无需等待即可结束。你几乎不应该使用 async void。
  • @Tratcher 谢谢告诉我原因!我永远不会那样使用:)
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 2015-10-07
  • 2011-06-02
  • 2019-04-17
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多