简体   繁体   English

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

[英]Set CORS on Windows Azure blob storage using ASP.NET

I'm attempting to set CORS properties on my Windows Azure blob storage account. 我正在尝试在我的Windows Azure blob存储帐户上设置CORS属性。 I'm using an ASP.NET server to send the PUT request. 我正在使用ASP.NET服务器发送PUT请求。

The server is sending back a Forbidden response, saying " Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. " 服务器正在发回Forbidden响应,说“ 服务器无法验证请求。请确保正确形成Authorization标头的值,包括签名。

So it must be something in my authentication header. 所以它必须是我的身份验证标题中的内容。 Here are the two functions I use to get the header. 以下是我用来获取标题的两个函数。

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

This is the controller action that sends the request. 这是发送请求的控制器操作。 The _mediaFactory.GetWindowsAzureCors method returns the contents of an XML file with my CORS request. _mediaFactory.GetWindowsAzureCors方法使用我的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;
}

What am I doing wrong? 我究竟做错了什么?

It's actually pretty simple. 它实际上非常简单。

First, add reference to Azure Storage Client library in your project. 首先,在项目中添加对Azure Storage Client库的引用。 If you're using Nuget, the package you would want to install is WindowsAzure.Storage . 如果您正在使用Nuget,您要安装的软件包是WindowsAzure.Storage

After that, the function which sets the CORS settings is SetServiceProperties . 之后,设置CORS设置的功能是SetServiceProperties Here's the sample code to do so: 以下是执行此操作的示例代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Stream 视频来自 Azure blob 存储和 ASP.NET 核心 3 - Stream videos from Azure blob storage and ASP.NET Core 3 Azure blob存储下载流返回“”asp.net - Azure blob storage download to stream returning “” asp.net 在asp.net中使用javascript在Azure BLOB存储上载期间,如何压缩视频? - How can i compress video during upload on Azure BLOB storage using javascript in asp.net? 使用asp.net Web API 2将媒体上传到Azure Blob存储 - upload media to azure blob storage using asp.net web api 2 使用ASP.NET Web API将图像添加到Azure blob存储失败 - Adding an image to Azure blob storage using ASP.NET Web API fails 如何使用ASP.NET MVC3在表中显示Azure Blob存储的所有图像? - How to display all the image from Azure Blob Storage in table using ASP.NET MVC3? 将 Azure blob 存储与 .NET 结合使用 - Using Azure blob storage with .NET 如何在windows azure中为Blob存储配置CORS设置 - How to configure CORS setting for Blob storage in windows azure 使用ASP.NET中的File Uploader将图像上传到Azure Blob? - Uploading Image to Azure Blob using File Uploader in ASP.NET? 在Azure上移动ASP.NET Web窗体站点,而无需再次对其进行编码以使用Azure Blob存储 - Moving an asp.net web forms site on azure without coding it again to use azure blob storage
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM