使用ASP.NET在Windows Azure blob存储上设置CORS

本文关键字:存储 设置 CORS blob Azure ASP NET Windows 使用 | 更新日期: 2023-09-27 18:02:51

我试图在我的Windows Azure blob存储帐户上设置CORS属性。我用的是ASP。. NET服务器发送PUT请求。

服务器正在发送一个Forbidden响应,表示"服务器未能验证请求"。"

一定是我的认证头中。下面是我用来获取标题的两个函数:

public string GetWindowsAzureAuthenticationHeader(string verb)
{
    string stringToSign = String.Format("{0}'n"
                                        + "'n" // content encoding
                                        + "'n" // content language
                                        + "'n" // content length
                                        + "'n" // content md5
                                        + "'n" // content type
                                        + "'n" // date
                                        + "'n" // if modified since
                                        + "'n" // if match
                                        + "'n" // if none match
                                        + "'n" // if unmodified since
                                        + "'n" // range
                                        + "x-ms-date:" + DateTime.UtcNow.ToString("R") + "'nx-ms-version:2013-08-15'n" // headers
                                        + "/{1}'ncomp:properties'nrestype:service", verb, CloudConfig.StorageAccountName);
    return SignThis(stringToSign, CloudConfig.StorageAccountKey, CloudConfig.StorageAccountName);
}
private string SignThis(string stringToSign, string key, string account)
{
    string signature;
    var unicodeKey = Convert.FromBase64String(key);
    using (var hmacSha256 = new HMACSHA256(unicodeKey))
    {
        var dataToHmac = Encoding.UTF8.GetBytes(stringToSign);
        signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
    }
    String authorizationHeader = String.Format(
        CultureInfo.InvariantCulture,
        "{0} {1}:{2}",
        "SharedKey",
        account,
        signature);
    return authorizationHeader;
}

发送请求的控制器动作。_mediaFactory。gettwindowsazurecors方法返回带有CORS请求的XML文件的内容。

var content = Encoding.UTF8.GetBytes(_mediaFactory.GetWindowsAzureCors(ControllerContext.HttpContext.Server));
var request = (HttpWebRequest)WebRequest.Create(CloudConfig.StorageAccountUri);
request.Method = "PUT";
request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R"));
request.Headers.Add("x-ms-version", "2013-08-15");
request.ContentType = "text/plain; charset=UTF-8";
request.Host = string.Format("{0}.blob.core.windows.net", CloudConfig.StorageAccountName);
request.Headers.Add("Authorization", _mediaFactory.GetWindowsAzureAuthenticationHeader(request.Method));
request.GetRequestStream().Write(content, 0, content.Length);
using (var response = (HttpWebResponse) request.GetResponse())
{
    model.StatusCode = response.StatusCode;
    model.Response = response.StatusDescription;
}

我做错了什么?

使用ASP.NET在Windows Azure blob存储上设置CORS

其实很简单。

首先,在项目中添加对Azure Storage Client库的引用。如果你正在使用Nuget,你想要安装的包是WindowsAzure.Storage

之后,设置CORS设置的功能为SetServiceProperties。下面是这样做的示例代码:

            CloudStorageAccount storageAccount = new CloudStorageAccount(new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accountKey), true);
            var blobClient = storageAccount.CreateCloudBlobClient();
            ServiceProperties blobServiceProperties = new ServiceProperties();
            blobServiceProperties.Cors.CorsRules.Add(new CorsRule(){
                AllowedHeaders = new List<string>() {"*"},
                ExposedHeaders = new List<string>() {"*"},
                AllowedMethods = CorsHttpMethods.Post | CorsHttpMethods.Put | ... Other Allowed Methods,
                AllowedOrigins = new List<string>() {"http://yourdomain.com", "https://yourdomain.com", "blah", "blah", "blah"},
                MaxAgeInSeconds = 3600,
            });
            blobClient.SetServiceProperties(blobServiceProperties);