无法上传到azure Blob存储:远程服务器返回错误:(400)错误请求

bun*_*eeb 13 c# azure azure-storage azure-storage-blobs

我正在尝试创建一个实用程序来从Internet下载文件并将其再次上载到Azure blob存储.Blob容器已经很好了; 但由于某种原因,当我试图将文件上传到存储时,我收到"Bad Request 400"异常...容器名称已创建,小写字母,所以特殊字符.但我仍然不知道为什么我会得到例外!

请帮忙.

注意:

  • 我没有使用任何模拟器......直接在云上测试.
  • 我的所有容器都有"公共容器"访问选项.

这是一个例外:

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.
Run Code Online (Sandbox Code Playgroud)

以下是代码:

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!");
      }
}
Run Code Online (Sandbox Code Playgroud)

编辑:存储异常

Microsoft.WindowsAzure.Storage.StorageException:远程服务器返回错误:(400)错误请求.---> System.Net.WebException:远程服务器返回错误:(400)错误请求.在System.Net.HttpWebRequest.GetRequestStream(TransportContext&context)at System.Net.HttpWebRequest.GetRequestStream()at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync [T](RESTCommand 1 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)选项,OperationContext operationContext)at TelawatAzureUtility.StorageService.<> c__DisplayClass4.b__12(任务任务)位于\ psf\Home\Documents\Visual Studio 14\Projects\Telawat Azure Utility\TelawatAzureUtility\StorageService.cs:第128行请求信息RequestID:RequestDate :2014年6月28日星期六20:12:14 GMT StatusMessage:错误请求

编辑2:请求信息:

在此输入图像描述

在此输入图像描述

编辑3:问题来自WebUtils ..我用下面的代码替换它,它的工作原理!我将添加weUtils代码,也许你可以帮助知道它有什么问题.

HttpClient client = new HttpClient();
var stream = await client.GetStreamAsync(url);
Run Code Online (Sandbox Code Playgroud)

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();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试这段代码时......"等待"永远不会完成或完成!

webUtil.DownloadAsync(url, downloadedFilePath).Wait()
Run Code Online (Sandbox Code Playgroud)

sid*_*ant 32

您是否尝试过在azure门户上手动创建容器?它对您可以为容器提供的名称有一些限制.

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

如果您请求具有无效名称的容器,则会导致您收到的(400)错误请求.所以检查你的"containerName"字符串.

  • 这对我有帮助.我在容器名称的开头只有一个大写字母,在Azure中它只是小写的. (4认同)

小智 21

我有同样的问题。我通过在存储配置中更改 TLS 版本来解决它;新的 TLS 版本 (1.2) 与旧版本的存储客户端不兼容。我将其更改为 1.0 并且可以正常工作。

存储的配置在 Azure 的门户中。

存储 -> 配置 -> TLS 版本:

门户中的存储配置