【问题标题】:Setting CORS rules using Azure.Storage.Blobs使用 Azure.Storage.Blobs 设置 CORS 规则
【发布时间】:2020-11-18 09:11:16
【问题描述】:

我正在尝试从已弃用的 Microsoft.WindowsAzure.Storage 迁移到 Azure.Storage。在我的 API 应用程序中,我有一个方法,我偶尔会调用它以编程方式在我的 Azure 存储帐户中设置 CORS 规则。

如何使用新的Azure.Storage.BlobsCORS 规则添加到属性中?

我在Microsoft.WindowsAzure.Storage 下工作的原始代码如下。在下面的代码中,_clientCloudBlobClient 的一个实例。我知道在Azure.Storage.Blobs 中,我需要使用我现在使用的BlobServiceClient,但正如我所说,以下代码的某些部分不起作用,因为某些方法/属性不再存在。我确定他们被转移到其他地方,但我无法弄清楚在哪里。

public async Task ConfigureCors()
{
    var ALLOWED_CORS_ORIGINS = new List<String> { "http://localhost:49065", "https://myappdomain.com", "https://www.myappdomain", "https://login.microsoftonline.com" };
    var ALLOWED_CORS_HEADERS = new List<String> { "x-ms-meta-qqfilename", "Content-Type", "x-ms-blob-type", "x-ms-blob-content-type" };
    const CorsHttpMethods ALLOWED_CORS_METHODS = CorsHttpMethods.Get | CorsHttpMethods.Delete | CorsHttpMethods.Put | CorsHttpMethods.Options;
    const int ALLOWED_CORS_AGE_DAYS = 5;

    var properties = await _client.GetServicePropertiesAsync();

    properties.DefaultServiceVersion = "2013-08-15";
    await _client.SetServicePropertiesAsync(properties);

    var addRule = true;
    if (addRule)
    {
       var ruleWideOpenWriter = new CorsRule()
       {
           AllowedHeaders = ALLOWED_CORS_HEADERS,
           AllowedOrigins = ALLOWED_CORS_ORIGINS,
           AllowedMethods = ALLOWED_CORS_METHODS,
           MaxAgeInSeconds = (int)TimeSpan.FromDays(ALLOWED_CORS_AGE_DAYS).TotalSeconds
       };
       properties.Cors.CorsRules.Clear();
       properties.Cors.CorsRules.Add(ruleWideOpenWriter);
       await _client.SetServicePropertiesAsync(properties);
    }
}

看起来我可以通过将_client.GetServicePropertiesAsync() 更改为_client.GetPropertiesAsync() 来获取和设置属性,但DefaultServiceVersion 不再存在。另外我似乎找不到设置CORS 规则的正确方法。

非常感谢您的建议。谢谢!

【问题讨论】:

    标签: azure cors azure-storage azure-blob-storage


    【解决方案1】:

    使用Azure.Storage.Blobs时可以使用下面的代码(我用的是同步方式,如果需要请改成异步方式):

            var properties = blobServiceClient.GetProperties().Value;
    
            properties.DefaultServiceVersion = "xxx";
    
            BlobCorsRule rule = new BlobCorsRule();
            rule.AllowedHeaders= "x-ms-meta-qqfilename,Content-Type,x-ms-blob-type,x-ms-blob-content-type";
            rule.AllowedMethods = "GET,DELETE,PUT,OPTIONS";
            rule.AllowedOrigins = "http://localhost:49065,https://myappdomain.com,https://www.myappdomain,https://login.microsoftonline.com";
            rule.MaxAgeInSeconds = 3600; // in seconds
    
            properties.Cors.Add(rule);
    
            blobServiceClient.SetProperties(properties);
    

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 2021-06-26
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 2021-01-08
    • 2017-06-15
    • 1970-01-01
    • 2018-03-10
    • 2014-01-05
    相关资源
    最近更新 更多