简体   繁体   English

如何在.Net Core中使用REST API访问Azure表存储

[英]How to access azure table storage using REST API in .Net Core

I want to access data from azure table storage ,but i couldn't access using Net core .But it's possible using .Net Framework. 我想从azure表存储访问数据,但是我无法使用Net core访问。但是使用.Net Framework是可能的。

Below code was written in .Net Framework 下面的代码是用.Net Framework编写的

var sharedKey = Convert.FromBase64String("AccountKey");
        var request = WebRequest.Create("http://accountname.table.core.windows.net/tablename");
        request.ContentLength = 0;
        request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture));
        var resource = request.RequestUri.PathAndQuery;
        if (resource.Contains("?"))
        {
            resource = resource.Substring(0, resource.IndexOf("?"));
        }

        string stringToSign = string.Format("{0}\n/{1}{2}",
                request.Headers["x-ms-date"],
                 "accountname",
                resource
            );
        var hasher = new HMACSHA256(sharedKey);
        string signedSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        string authorizationHeader = string.Format("{0} {1}:{2}", "SharedKeyLite", "accountname", signedSignature);
        request.Headers.Add("Authorization", authorizationHeader);
        var response = request.GetResponse();
        return response;

As far as I know, there are some differences between .Net Core and .Net Standard when using REST API. 据我所知,使用REST API时.Net Core和.Net Standard之间存在一些差异。

  1. In .NET 4.5 there are some properties you have to set on the HttpWebRequest object and you can't just set them in the headers. 在.NET 4.5中,必须在HttpWebRequest对象上设置一些属性,而不能仅在标头中设置它们。 Well, in core they decided to reverse course and you have to use the header collection. 好吧,从根本上讲,他们决定撤退路线,您必须使用标头集合。

    .NET Core: request.Headers["x-ms-version"] = "2015-04-05"; .NET Core: request.Headers["x-ms-version"] = "2015-04-05";

    .NET 4.5: request.Headers.Add("x-ms-version", "2015-04-05"); .NET 4.5: request.Headers.Add("x-ms-version", "2015-04-05");

  2. .NET Core only support WebResponse.GetResponseAsync() method, so you could only use the async way to get the result. .NET Core仅支持WebResponse.GetResponseAsync()方法,因此您只能使用异步方法来获取结果。

    Like below: Task<WebResponse> response = request.GetResponseAsync(); HttpWebResponse responseresult = (HttpWebResponse)response.Result; 如下所示: Task<WebResponse> response = request.GetResponseAsync(); HttpWebResponse responseresult = (HttpWebResponse)response.Result; Task<WebResponse> response = request.GetResponseAsync(); HttpWebResponse responseresult = (HttpWebResponse)response.Result;

More details, you could refer to follow codes: 更多详细信息,您可以参考以下代码:

string storageAccount = "storageAccount";
        string accessKey = "accessKey";
        string resourcePath = "TableSample()";
        string uri = @"https://" + storageAccount + ".table.core.windows.net/" + resourcePath;
        // Web request 
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
        request.Method = "GET";
        request.ContentType = "application/json";
        request.Accept = "application/json;odata=nometadata";
        request.Headers["x-ms-date"] = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);
        request.Headers["x-ms-version"] = "2015-04-05";
        string stringToSign = request.Headers["x-ms-date"] + "\n"; 
        int query = resourcePath.IndexOf("?");
        if (query > 0)
        {
            resourcePath = resourcePath.Substring(0, query);
        }
        stringToSign += "/" + storageAccount + "/" + resourcePath;
        System.Security.Cryptography.HMACSHA256 hasher = new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(accessKey));
        string strAuthorization = "SharedKeyLite " + storageAccount + ":" + System.Convert.ToBase64String(hasher.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToSign)));


        request.Headers["Authorization"] = strAuthorization;

        Task<WebResponse> response = request.GetResponseAsync();
        HttpWebResponse responseresult = (HttpWebResponse)response.Result;

            using (System.IO.StreamReader r = new System.IO.StreamReader(responseresult.GetResponseStream()))
            {
                string jsonData = r.ReadToEnd();
                Console.WriteLine(jsonData);
           }
        Console.ReadLine();

Result: 结果: 在此处输入图片说明

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM