无法上传到Azure Blob存储:远程服务器返回错误:(400)错误的请求 [英] Cannot upload to azure Blob Storage: The remote server returned an error: (400) Bad Request

查看:71
本文介绍了无法上传到Azure Blob存储:远程服务器返回错误:(400)错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a utility to download file from the internet and upload it again to Azure blob storage. Blob containers already created well; But for some reason i'm getting "Bad Request 400" exception when i tried to upload the file to storage ... Container name is created, small letters, so special characters. But I still do not know why i'm getting the 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:远程服务器返回错误:(400)错误的请求.---> System.Net.WebException:远程服务器返回错误:(400)错误的请求.在System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)在System.Net.HttpWebRequest.GetRequestStream()在Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync [T](RESTCommand <代码> 1 cmd,IRetryPolicy策略,OperationContext operationContext)---内部异常堆栈跟踪的结尾---在Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync [T](RESTCommand 1 cmd,IRetryPolicy策略,OperationContext operationContext)在Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStreamHelper(流源,可空1的长度,AccessCondition accessCondition,BlobRequestOptions选项,OperationContext operationContext)在Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromStream(流源,AccessCondition accessCondition,BlobRequestOptions选项,OperationContext operationContext)在TelawatAzureUtility.StorageService中.<> c__DisplayClass4.b__12(任务任务)位于\ psf \ Home \ Documents \ Visual Studio 14 \ Projects \ Telawat Azure Utility \ TelawatAzureUtility \ StorageService.cs:第128行索取资料要求编号:RequestDate:Sat,28 Jun 2014 20:12:14 GMTStatusMessage:错误请求

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

请求信息:

问题出自WebUtils ..我用下面的代码替换了它,并且有效!我将添加weUtils代码,也许您可​​以帮助了解它的问题.

Edit 3: The problem comes from WebUtils .. I replaced it with below code and it works! I will add weUtils code, maybe you can help to know what is the problem with it.

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

WebUtils代码:

WebUtils Code:

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();
                }
            }
        }
    }
}

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

Also when I tried this code ... the 'Wait' will never finish or completed!

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

推荐答案

您是否尝试过在Azure门户上手动创建容器?您可以给容器命名的名称有一些限制.

Have you tried creating a container manually on azure portal? It has some limitations on what name you can give containers.

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

For example: Container name cannot contain upper case letters.

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

If you request a container with an invalid name, it will result in (400) Bad Request, which you are getting. So check your "containerName" string.

这篇关于无法上传到Azure Blob存储:远程服务器返回错误:(400)错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆