2015-10-03 2 views
0

Я хочу включить CORS в свою учетную запись Azure Blob Storage. Я пытаюсь следовать этому образцу https://code.msdn.microsoft.com/Windows-Azure-Storage-CORS-45e5ce76Включение CORS для хранения Azure Blob

Сервер выдает неверный запрос System.Net.WebException (400).

Это мой код:

Global.asax.cs

protected void Application_Start() 
{ 
    Database.SetInitializer<dynazzy.Models.DAL>(null); 
    AreaRegistration.RegisterAllAreas(); 

    WebApiConfig.Register(GlobalConfiguration.Configuration); 
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
    BundleConfig.RegisterBundles(BundleTable.Bundles); 
    AzureCommon.InitializeAccountPropeties(); 
} 

AzureCommon.cs

using System.Collections.Generic; 
using Microsoft.WindowsAzure.Storage; 
using Microsoft.WindowsAzure.Storage.Blob; 
using Microsoft.WindowsAzure.Storage.Shared.Protocol; 
using Microsoft.WindowsAzure.Storage.Table; 
using Microsoft.WindowsAzure; 

namespace dynazzy 
{ 
    /// <summary> 
    /// This class contains the Windows Azure Storage initialization and common functions. 
    /// </summary> 
    public class AzureCommon 
    { 
     private static CloudStorageAccount StorageAccount = CloudStorageAccount.DevelopmentStorageAccount; 

     public static CloudBlobClient BlobClient 
     { 
      get; 
      private set; 
     } 

     public static CloudTableClient TableClient 
     { 
      get; 
      private set; 
     } 

     public static CloudBlobContainer ImagesContainer 
     { 
      get; 
      private set; 
     } 

     public const string ImageContainerName = "someimagescontainer"; 

     /// <summary> 
     /// Initialize Windows Azure Storage accounts and CORS settings. 
     /// </summary> 
     public static void InitializeAccountPropeties() 
     { 
      BlobClient = StorageAccount.CreateCloudBlobClient(); 
      TableClient = StorageAccount.CreateCloudTableClient(); 

      InitializeCors(BlobClient, TableClient); 

      ImagesContainer = BlobClient.GetContainerReference(AzureCommon.ImageContainerName); 
      ImagesContainer.CreateIfNotExists(BlobContainerPublicAccessType.Container); 
     } 

     /// <summary> 
     /// Initialize Windows Azure Storage CORS settings. 
     /// </summary> 
     /// <param name="blobClient">Windows Azure storage blob client</param> 
     /// <param name="tableClient">Windows Azure storage table client</param> 
     private static void InitializeCors(CloudBlobClient blobClient, CloudTableClient tableClient) 
     { 
      // CORS should be enabled once at service startup 
      ServiceProperties blobServiceProperties = new ServiceProperties(); 
      ServiceProperties tableServiceProperties = new ServiceProperties(); 

      // Nullifying un-needed properties so that we don't 
      // override the existing ones 
      blobServiceProperties.HourMetrics = null; 
      tableServiceProperties.HourMetrics = null; 
      blobServiceProperties.MinuteMetrics = null; 
      tableServiceProperties.MinuteMetrics = null; 
      blobServiceProperties.Logging = null; 
      tableServiceProperties.Logging = null; 

      // Enable and Configure CORS 
      ConfigureCors(blobServiceProperties); 
      ConfigureCors(tableServiceProperties); 

      // Commit the CORS changes into the Service Properties 
      blobClient.SetServiceProperties(blobServiceProperties); 
      tableClient.SetServiceProperties(tableServiceProperties); 
     } 

     /// <summary> 
     /// Adds CORS rule to the service properties. 
     /// </summary> 
     /// <param name="serviceProperties">ServiceProperties</param> 
     private static void ConfigureCors(ServiceProperties serviceProperties) 
     { 
      serviceProperties.Cors = new CorsProperties(); 
      serviceProperties.Cors.CorsRules.Add(new CorsRule() 
      { 
       AllowedHeaders = new List<string>() { "*" }, 
       AllowedMethods = CorsHttpMethods.Put | CorsHttpMethods.Get | CorsHttpMethods.Head | CorsHttpMethods.Post, 
       AllowedOrigins = new List<string>() { "*" }, 
       ExposedHeaders = new List<string>() { "*" }, 
       MaxAgeInSeconds = 1800 // 30 minutes 
      }); 
     } 
    } 
} 

WebApiConfig.cs

public static void Register(HttpConfiguration config) 
{ 

    config.Routes.MapHttpRoute(
     name: "DefaultApi", 
     routeTemplate: "api/{controller}/{id}", 
     defaults: new { id = RouteParameter.Optional } 
    ); 

} 
+0

Возможно, стоит упомянуть, где вы кодируете исключение –

ответ

0

Чтобы включить CORS, вы необходимо установить соответствующий сервис свойства льда с использованием версии 2013-08-15 или более поздней версии для служб Blob, Queue и Table или версии 2015-02-21 или для службы File. Вы включаете CORS, добавляя правила CORS к свойствам службы.

Для получения дополнительной информации о том, как включить или отключить CORS для службы и как установить правила CORS, пожалуйста, обратитесь к Set Blob Service Properties

Вот пример одного правила CORS, задаются с помощью операции в Properties Set Service:

<Cors>  
     <CorsRule> 
      <AllowedOrigins>http://www.contoso.com, http://www.fabrikam.com</AllowedOrigins> 
      <AllowedMethods>PUT,GET</AllowedMethods> 
      <AllowedHeaders>x-ms-meta-data*,x-ms-meta-target*,x-ms-meta-abc</AllowedHeaders> 
      <ExposedHeaders>x-ms-meta-*</ExposedHeaders> 
      <MaxAgeInSeconds>200</MaxAgeInSeconds> 
    </CorsRule> 
<Cors> 
0

После борьбы с этим в течение почти одного дня, я понял, что ошибка связана с неподдерживаемой версией Azure Storage SDK. Я отказался от версии 3.0.2.0 своего пакета Microsoft.WindowsAzure.Storage SDK, и теперь я могу поговорить с моим эмулятором.

 Смежные вопросы

  • Нет связанных вопросов^_^