c# - 无法上传到Azure Blob存储: The remote server returned an error: (400) Bad Request

标签 c# azure azure-storage azure-blob-storage

我正在尝试创建一个实用程序来从 Internet 下载文件并将其再次上传到 Azure blob 存储。 Blob 容器已经创建良好;但由于某种原因,当我尝试将文件上传到存储时,我收到“错误请求 400”异常...创建了容器名称,小写字母,特殊字符。但我仍然不知道为什么我会遇到异常!

请帮忙。

注意:

  • 我没有使用任何模拟器...直接在云端测试。
  • 我的所有容器都具有“公共(public)容器”访问选项。

这是一个异常(exception):

An exception of type 'Microsoft.WindowsAzure.Storage.StorageException' 
occurred in Microsoft.WindowsAzure.Storage.dll but was not handled in user code
Additional information: The remote server returned an error: (400) Bad Request.

这是代码:

foreach (var obj in objectsList)
{
     var containerName = obj.id.Replace("\"", "").Replace("_", "").Trim();
     CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);

     if (blobContainer.Exists())
     {
         var fileNamesArr = obj.fileNames.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

         foreach (var sora in fileNamesArr)
         {
             int soraInt = int.Parse(sora.Replace("\"", ""));
             String fileName = String.Format("{0}.mp3", soraInt.ToString("000"));

             var url = String.Format("http://{0}/{1}/{2}", obj.hostName.Replace("\"", ""), obj.id.Replace("\"", ""), fileName.Replace("\"", "")).ToLower();

             var tempFileName = "temp.mp3";

             var downloadedFilePath = Path.Combine(Path.GetTempPath(), tempFileName).ToLower();

             var webUtil = new WebUtils(url);
             await webUtil.DownloadAsync(url, downloadedFilePath).ContinueWith(task =>
             {
                 var blobRef = blobContainer.GetBlockBlobReference(fileName.ToLower());
                 blobRef.Properties.ContentType = GetMimeType(downloadedFilePath);

                 using (var fs = new FileStream(downloadedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                 {
                     blobRef.UploadFromStream(fs); // <--- Exception
                 }
             });
         }
      }
      else
      {
          throw new Exception(obj.id.Replace("\"", "") + " Container not exist!");
      }
}

编辑:存储异常

Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (400) Bad Request. ---> System.Net.WebException: The remote server returned an error: (400) Bad Request. at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) at System.Net.HttpWebRequest.GetRequestStream() at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext) --- End of inner exception stack trace --- at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext) at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStreamHelper(Stream source, Nullable`1 length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) at Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStream(Stream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) at TelawatAzureUtility.StorageService.<>c__DisplayClass4.b__12(Task task) in \psf\Home\Documents\Visual Studio 14\Projects\Telawat Azure Utility\TelawatAzureUtility\StorageService.cs:line 128 Request Information RequestID: RequestDate:Sat, 28 Jun 2014 20:12:14 GMT StatusMessage:Bad Request

编辑2:请求信息:

enter image description here

enter image description here

编辑3:问题来自WebUtils..我用下面的代码替换它并且它有效!我会添加weUtils代码,也许你可以帮助了解它的问题所在。

HttpClient client = new HttpClient();
var stream = await client.GetStreamAsync(url);

WebUtils 代码:

public class WebUtils
{
    private Lazy<IWebProxy> proxy;

    public WebUtils(String url)
    {
        proxy = new Lazy<IWebProxy>(() => string.IsNullOrEmpty(url) ? null : new WebProxy {
            Address = new Uri(url), UseDefaultCredentials = true });
    }

    public IWebProxy Proxy
    {
        get { return proxy.Value; }
    }

    public Task DownloadAsync(string requestUri, string filename)
    {
        if (requestUri == null)
            throw new ArgumentNullException("requestUri is missing!");

        return DownloadAsync(new Uri(requestUri), filename);
    }

    public async Task DownloadAsync(Uri requestUri, string filename)
    {
        if (filename == null)
            throw new ArgumentNullException("filename is missing!");

        if (Proxy != null)
        {
            WebRequest.DefaultWebProxy = Proxy;
        }

        using (var httpClient = new HttpClient())
        {
            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                using (Stream contentStream = await (await httpClient.SendAsync(request)).Content.ReadAsStreamAsync())
                {
                    using (var stream = new FileStream(filename, FileMode.Create, FileAccess.Write))
                    {
                        contentStream.CopyTo(stream);
                        stream.Flush();
                        stream.Close();
                    }
                    contentStream.Close();
                }
            }
        }
    }
}

此外,当我尝试此代码时......“等待”将永远不会完成或完成!

webUtil.DownloadAsync(url, downloadedFilePath).Wait()

最佳答案

您是否尝试过在 Azure 门户上手动创建容器?它对您可以为容器指定的名称有一些限制。

例如:容器名称不能包含大写字母。

如果您请求一个名称无效的容器,将会导致您收到的 (400) Bad Request。因此,请检查您的“containerName”字符串。

关于c# - 无法上传到Azure Blob存储: The remote server returned an error: (400) Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24470217/

相关文章:

azure - 使用单个 azure 应用程序服务托管多个应用程序/微服务有哪些限制/缺点?

azure - 如何在 Windows Azure 中创建备份

c# - 我如何在 ASP.NET MVC 3.0 项目中以正确的方式进行缓存?

c# - 缓存或不缓存 - GetCustomAttributes

java - Azure insert 不会添加实体的新属性 (Java)

json - Arm 模板中的 copyindex() 错误

c# - 如何在不丢失比例的情况下使图片具有特定的宽度和高度?

c# - 在集合中封装引用类型

Azure DevOps 设置多个源以恢复包

c# - 避免在 Azure 表存储中进行新的更新插入