文件上传到WebAPI& Azure抛出HttpException

时间:2015-01-22 09:58:28

标签: c# azure file-upload asp.net-web-api azure-storage-blobs

有时,当来自中国的用户将小文件(100-200kB)上传到将文件直接传递到Azure blob的WebAPI服务时,我会收到此异常:

System.Web.HttpException: The client is disconnected because the underlying request has been completed. There is no longer an HttpContext available.

控制器代码如下所示:

[HttpPost]
public async Task<IHttpActionResult> Upload()
{
    var stream = await Request.Content.ReadAsStreamAsync();

    var guid = Guid.NewGuid().ToString();
    var blob = /*CloudBlobContainer*/.GetBlockBlobReference(guid);

    blob.Properties.ContentType = Request.Content.Headers.ContentType.MediaType;
    blob.UploadFromStream(stream);

    return Ok(guid);
}

堆栈跟踪:

System.Web.HttpException: The client is disconnected because the underlying request has been completed.  There is no longer an HttpContext available.

at System.Web.HttpBufferlessInputStream.Read(Byte[] buffer, Int32 offset, Int32 count)

at System.Web.Http.WebHost.SeekableBufferedRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count)

at Microsoft.WindowsAzure.Storage.Core.Util.StreamExtensions.WriteToSync[T](Stream stream, Stream toStream, Nullable`1 copyLength, Nullable`1 maxLength, Boolean calculateMd5, Boolean syncRead, ExecutionState`1 executionState, StreamDescriptor streamCopyState)

at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStreamHelper(Stream source, Nullable`1 length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)

at .Controllers.FileController.<Upload>d__5.MoveNext()

假设这是只是糟糕的互联网连接是否安全?在那种情况下,我可以抓住并忽略它。客户端有一个安全的重试机制,以防上传出错。

或者我的代码有问题吗?

1 个答案:

答案 0 :(得分:1)

代码看起来不错,在这种情况下进行重试是有道理的。

您可能还想为存储帐户启用Storage Analytics,因此,如果下次遇到此异常,您将能够通过查看日志来判断请求是否已到达Azure存储服务器端,请参阅有关详细信息,请参阅下面帖子中的“端到端跟踪”部分。

http://azure.microsoft.com/en-us/documentation/articles/storage-monitoring-diagnosing-troubleshooting/