【问题标题】:"Index was out of range" Error at await Request.Content.ReadAsMultipartAsync(provider)“索引超出范围”等待 Request.Content.ReadAsMultipartAsync(provider) 时出错
【发布时间】:2018-04-02 09:21:59
【问题描述】:

我已关注此tutorial 从 Azure Blob 存储上传/下载 Blob。

在我实现承载令牌身份验证(OAuth)之前,代码运行良好

我在从邮递员上传任何文件时遇到错误。以下是错误描述。

{ “消息”:“发生错误。详细信息:索引超出范围。必须为非负数且小于 集合。\r\n参数名称:索引" }

但是,文件已成功上传到我的 Blob 帐户中。但是,我仍然不断出现错误。

我已附上调试时获得的错误详细信息的图像。

我在上传控制器中提示错误的区域

 try
            {
                await Request.Content.ReadAsMultipartAsync(provider);

            }
            catch (Exception ex)
            {
                return BadRequest($"An error has occured. Details: {ex.Message}");
            }

我的 AzureStorageMultipartFormDataStreamProvider 类继承自 MultipartFormDataStreamProvider

public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {


                if (parent == null) throw new ArgumentNullException(nameof(parent));
                if (headers == null) throw new ArgumentNullException(nameof(headers));


            // Generate a new filename for every new blob

            var fileName = Guid.NewGuid().ToString();
            CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(fileName);
            headers.ContentLength = 0;

            if (headers.ContentType != null)
                {
                    // Set appropriate content type for your uploaded file
                    blob.Properties.ContentType = headers.ContentType.MediaType;
                }

                this.FileData.Add(new MultipartFileData(headers, blob.Name));

                return blob.OpenWrite();         
        }

为了实现 Oauth2.0 身份验证,我刚刚在我的项目中添加了 Startup .cs 和 Startup.Auth.cs(带有所需的 NuGet 包 Owin

这是我的 StackTrace

在 System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument 参数,ExceptionResource 资源)在 System.Collections.Generic.List1.get_Item(Int32 index) at System.Net.Http.MultipartFormDataStreamProvider.<ExecutePostProcessingAsync>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__01.MoveNext() --- 从先前引发异常的位置结束堆栈跟踪 --- 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime。 CompilerServices.TaskAwaiter`1.GetResult() 在 DemoAzureStorage.Controllers.UploadController.d__1.MoveNext()

【问题讨论】:

  • 共享调用堆栈/堆栈跟踪。
  • @rene 更新了堆栈跟踪

标签: c# asp.net-web-api oauth-2.0 azure-blob-storage bearer-token


【解决方案1】:

根据您的描述,我已经创建了一个测试演示(所有安装的软件包都是最新的),它运行良好。

我使用了带有谷歌登录的 asp.net web api 和 AzureStorageMultipartFormDataStreamProvider 作为你的展示。

我的上传文件控制器代码如下:

public class UploadController : ApiController
{
    private const string Container = "mycontainer";

    [HttpPost]
    public async Task<IHttpActionResult> UploadFile()
    {
        if (!Request.Content.IsMimeMultipartContent("form-data"))
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }


        var storageAccount = CloudStorageAccount.Parse("connection string");
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

        CloudBlobContainer imagesContainer = blobClient.GetContainerReference(Container);
        var provider = new AzureStorageMultipartFormDataStreamProvider(imagesContainer);

        try
        {
            await Request.Content.ReadAsMultipartAsync(provider);
        }
        catch (Exception ex)
        {
            return BadRequest($"An error has occured. Details: {ex.Message}");
        }

        // Retrieve the filename of the file you have uploaded
        var filename = provider.FileData.FirstOrDefault()?.LocalFileName;
        if (string.IsNullOrEmpty(filename))
        {
            return BadRequest("An error has occured while uploading your file. Please try again.");
        }

        return Ok($"File: {filename} has successfully uploaded");
    }
}

AzureStorageMultipartFormDataStreamProvider 类:

public class AzureStorageMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    private readonly CloudBlobContainer _blobContainer;
    private readonly string[] _supportedMimeTypes = { "image/png", "image/jpeg", "image/jpg" };

    public AzureStorageMultipartFormDataStreamProvider(CloudBlobContainer blobContainer) : base("azure")
    {
        _blobContainer = blobContainer;
    }

    public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
    {
        if (parent == null) throw new ArgumentNullException(nameof(parent));
        if (headers == null) throw new ArgumentNullException(nameof(headers));

        if (!_supportedMimeTypes.Contains(headers.ContentType.ToString().ToLower()))
        {
            throw new NotSupportedException("Only jpeg and png are supported");
        }

        // Generate a new filename for every new blob
        var fileName = Guid.NewGuid().ToString();

        CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(fileName);

        if (headers.ContentType != null)
        {
            // Set appropriate content type for your uploaded file
            blob.Properties.ContentType = headers.ContentType.MediaType;
        }

        this.FileData.Add(new MultipartFileData(headers, blob.Name));

        return blob.OpenWrite();
    }

结果如下图所示:

如果可能,您可以创建一个测试项目并将其推送到 github 或一个驱动器,以便我们重现您的问题。

Packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Antlr" version="3.4.1.9004" targetFramework="net46" />
  <package id="bootstrap" version="3.0.0" targetFramework="net46" />
  <package id="EntityFramework" version="6.1.3" targetFramework="net46" />
  <package id="jQuery" version="1.10.2" targetFramework="net46" />
  <package id="Knockout.Validation" version="1.0.1" targetFramework="net46" />
  <package id="knockoutjs" version="2.3.0" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights" version="2.2.0" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.0.6" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.2.0" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.2.0" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights.Web" version="2.2.0" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.2.0" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.2.0" targetFramework="net46" />
  <package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net46" />
  <package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net46" />
  <package id="Microsoft.AspNet.Identity.Owin" version="2.2.1" targetFramework="net46" />
  <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.HelpPage" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net46" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net46" />
  <package id="Microsoft.Azure.KeyVault.Core" version="1.0.0" targetFramework="net46" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.5" targetFramework="net46" />
  <package id="Microsoft.Data.Edm" version="5.8.2" targetFramework="net46" />
  <package id="Microsoft.Data.OData" version="5.8.2" targetFramework="net46" />
  <package id="Microsoft.Data.Services.Client" version="5.8.2" targetFramework="net46" />
  <package id="Microsoft.Net.Compilers" version="2.1.0" targetFramework="net46" developmentDependency="true" />
  <package id="Microsoft.Owin" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Security" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Security.Cookies" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Security.Facebook" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Security.Google" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Security.MicrosoftAccount" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Security.OAuth" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Owin.Security.Twitter" version="3.0.1" targetFramework="net46" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net46" />
  <package id="Modernizr" version="2.6.2" targetFramework="net46" />
  <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net46" />
  <package id="Owin" version="1.0" targetFramework="net46" />
  <package id="Respond" version="1.2.0" targetFramework="net46" />
  <package id="Sammy.js" version="0.7.4" targetFramework="net46" />
  <package id="System.ComponentModel.EventBasedAsync" version="4.0.11" targetFramework="net46" />
  <package id="System.Dynamic.Runtime" version="4.0.0" targetFramework="net46" />
  <package id="System.Linq.Queryable" version="4.0.0" targetFramework="net46" />
  <package id="System.Net.Requests" version="4.0.11" targetFramework="net46" />
  <package id="System.Spatial" version="5.8.2" targetFramework="net46" />
  <package id="WebGrease" version="1.5.2" targetFramework="net46" />
  <package id="WindowsAzure.Storage" version="8.5.0" targetFramework="net46" />
</packages>

【讨论】:

  • 我已经在 Github 上发布了我的项目。github.com/jayendranarumugam/MyProject
  • 我使用密码grant_type.So请使用下面的access_token { “ACCESS_TOKEN”: “qOErEnLSbDjQW8XaUnSEImDNRTe8WRVJHbqXEUQxJw4EiqHoybw4Jc4gBYJkClORNCprnPbJxJ0WGumBcq-i4TMom-HxOBGgYgneYbTUKw5zyrWSwTEdtPsfjNzzYxCtcwSj4a9tEEj_j8czKcrauM9lhJMHcx4p9jS-nWkAAZepvJKJx8fqQUZgyo4tjysDSpNJBTAsTMgw2Z8xZ3QXGW06OzYW2LeOkNUmFp0PWY2sj0Suykgz0G2Lw7KXBar7okFHLV9KtZPArAWsOfFAvi-c84y6TjqzZkZnU5n5jmAy_Z3A3j1Ahww7Kz4p-p6lu7dYFw”, “token_type”: “承载”,“ expires_in": 60899, "refresh_token": "a868cb78-4773-4fbf-888e-38a6b0a11700" }
  • 我无法在我这边运行您的应用程序。你能分享一个建筑完整的应用程序吗?另外,我发现你的Owin版本是2.1,建议你更新到3.1再试一次。
  • 更改 Owin 版本不起作用。等等我给你分享一个构建完整的应用程序
  • 重现您的问题后,我找到了原因。我发现你的 Microsoft.AspNet.WebApi 版本是 5.0.0。我想这可能与 MultipartFormDataStreamProvider 类有问题。我建议您可以尝试将 Microsoft.AspNet.WebApi 版本上传到 5.2.3。它会很好用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多