Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中使用PUT请求将内容写入azure存储上的文件#_C#_.net_Azure_Rest_Azure Files - Fatal编程技术网

C# 在C中使用PUT请求将内容写入azure存储上的文件#

C# 在C中使用PUT请求将内容写入azure存储上的文件#,c#,.net,azure,rest,azure-files,C#,.net,Azure,Rest,Azure Files,我正在尝试向Azure存储文件发出put请求,我想在其中添加一些简单的内容。我更改了URL并在URL的末尾添加了?comp=range,但得到了403错误的响应。我已经在.net中创建了一个基本的控制台应用程序 我的标题是: const string requestMethod = "PUT"; string urlPath = strShareName + "/" + "rahila.csv?comp=range";//+ "?comp=range HTTP/1.1

我正在尝试向Azure存储文件发出put请求,我想在其中添加一些简单的内容。我更改了URL并在URL的末尾添加了
?comp=range
,但得到了403错误的响应。我已经在.net中创建了一个基本的控制台应用程序

我的标题是:

 const string requestMethod = "PUT";
            string urlPath = strShareName + "/" + "rahila.csv?comp=range";//+ "?comp=range  HTTP/1.1";
            String canonicalizedResource = String.Format("/{0}/{1}/{2}", StorageAccountName, strShareName, strFileName);
            try
            {
                //GetWebRequest(requestMethod, urlPath, canonicalizedResource, "CreateFile");
                HttpWebRequest request = null;
                try
                {
                    const string type = "file";
                    string MethodType = "CreateFile";
                    const string msVersion = "2015-04-05";
                    String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
                    String canonicalizedHeaders = "";
                    string data = "rahila sted";
                    canonicalizedHeaders = String.Format("x-ms-date:{0}\nx-ms-version:{1}", dateInRfc1123Format, msVersion);
                    if (MethodType == "CreateFile")
                    {
                        canonicalizedHeaders = String.Format("x-ms-content-length:65536\nx-ms-date:{0}\nx-ms-type:file\nx-ms-version:{1}", dateInRfc1123Format, msVersion);
                    }

                    String stringToSign = "";


                    stringToSign = String.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canonicalizedHeaders, canonicalizedResource);

                    if (String.IsNullOrEmpty(stringToSign))
                    {
                        throw new ArgumentNullException("canonicalizedString");
                    }

                    String signature;

                    if (String.IsNullOrEmpty(stringToSign))
                    {
                        throw new ArgumentNullException("unsignedString");
                    }

                    if (Convert.FromBase64String(StorageKey) == null)
                    {
                        throw new ArgumentNullException("key");
                    }

                    Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(stringToSign);
                    using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageKey)))
                    {
                        signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
                    }


                    String authorizationHeader = String.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}",
                                                               StorageScheme,
                                                               StorageAccountName, signature);
Uri uri = new Uri(FileEndPoint + urlPath);
request = (HttpWebRequest)WebRequest.Create(uri);
if (requestMethod != "Get")
{
    request.ContentLength = data.Length;
}
// string data = "Hello testing";
//int a= ((data.Length) + 1);

request.Method = "PUT";//requestMethod;
request.Headers.Add("x-ms-write", "update");
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", msVersion);
request.Headers.Add("x-ms-range", "bytes=0-65535"); // + ((data.Length) - 1));
request.Headers.Add("Authorization", authorizationHeader);
我得到异常的那一行是粗体格式的

HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
string returnString = response.StatusCode.ToString();

有谁能帮我解决这个问题,或者指导我如何在不使用azure客户端API的情况下将内容写入azure存储上的简单文件。

更新12/19:

 const string requestMethod = "PUT";
            string urlPath = strShareName + "/" + "rahila.csv?comp=range";//+ "?comp=range  HTTP/1.1";
            String canonicalizedResource = String.Format("/{0}/{1}/{2}", StorageAccountName, strShareName, strFileName);
            try
            {
                //GetWebRequest(requestMethod, urlPath, canonicalizedResource, "CreateFile");
                HttpWebRequest request = null;
                try
                {
                    const string type = "file";
                    string MethodType = "CreateFile";
                    const string msVersion = "2015-04-05";
                    String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
                    String canonicalizedHeaders = "";
                    string data = "rahila sted";
                    canonicalizedHeaders = String.Format("x-ms-date:{0}\nx-ms-version:{1}", dateInRfc1123Format, msVersion);
                    if (MethodType == "CreateFile")
                    {
                        canonicalizedHeaders = String.Format("x-ms-content-length:65536\nx-ms-date:{0}\nx-ms-type:file\nx-ms-version:{1}", dateInRfc1123Format, msVersion);
                    }

                    String stringToSign = "";


                    stringToSign = String.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canonicalizedHeaders, canonicalizedResource);

                    if (String.IsNullOrEmpty(stringToSign))
                    {
                        throw new ArgumentNullException("canonicalizedString");
                    }

                    String signature;

                    if (String.IsNullOrEmpty(stringToSign))
                    {
                        throw new ArgumentNullException("unsignedString");
                    }

                    if (Convert.FromBase64String(StorageKey) == null)
                    {
                        throw new ArgumentNullException("key");
                    }

                    Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(stringToSign);
                    using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageKey)))
                    {
                        signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
                    }


                    String authorizationHeader = String.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}",
                                                               StorageScheme,
                                                               StorageAccountName, signature);
Uri uri = new Uri(FileEndPoint + urlPath);
request = (HttpWebRequest)WebRequest.Create(uri);
if (requestMethod != "Get")
{
    request.ContentLength = data.Length;
}
// string data = "Hello testing";
//int a= ((data.Length) + 1);

request.Method = "PUT";//requestMethod;
request.Headers.Add("x-ms-write", "update");
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", msVersion);
request.Headers.Add("x-ms-range", "bytes=0-65535"); // + ((data.Length) - 1));
request.Headers.Add("Authorization", authorizationHeader);
使用将内容上载到azure文件时,您可以遵循以下代码(我假设您已经在azure文件共享上创建了一个文件,并且它的内容长度大于正在上载的内容):

然后在
Main()
方法中,您可以调用
UploadText()
方法,它在我这边工作


旧版:

 const string requestMethod = "PUT";
            string urlPath = strShareName + "/" + "rahila.csv?comp=range";//+ "?comp=range  HTTP/1.1";
            String canonicalizedResource = String.Format("/{0}/{1}/{2}", StorageAccountName, strShareName, strFileName);
            try
            {
                //GetWebRequest(requestMethod, urlPath, canonicalizedResource, "CreateFile");
                HttpWebRequest request = null;
                try
                {
                    const string type = "file";
                    string MethodType = "CreateFile";
                    const string msVersion = "2015-04-05";
                    String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
                    String canonicalizedHeaders = "";
                    string data = "rahila sted";
                    canonicalizedHeaders = String.Format("x-ms-date:{0}\nx-ms-version:{1}", dateInRfc1123Format, msVersion);
                    if (MethodType == "CreateFile")
                    {
                        canonicalizedHeaders = String.Format("x-ms-content-length:65536\nx-ms-date:{0}\nx-ms-type:file\nx-ms-version:{1}", dateInRfc1123Format, msVersion);
                    }

                    String stringToSign = "";


                    stringToSign = String.Format("{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}", requestMethod, canonicalizedHeaders, canonicalizedResource);

                    if (String.IsNullOrEmpty(stringToSign))
                    {
                        throw new ArgumentNullException("canonicalizedString");
                    }

                    String signature;

                    if (String.IsNullOrEmpty(stringToSign))
                    {
                        throw new ArgumentNullException("unsignedString");
                    }

                    if (Convert.FromBase64String(StorageKey) == null)
                    {
                        throw new ArgumentNullException("key");
                    }

                    Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(stringToSign);
                    using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageKey)))
                    {
                        signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
                    }


                    String authorizationHeader = String.Format(CultureInfo.InvariantCulture, "{0} {1}:{2}",
                                                               StorageScheme,
                                                               StorageAccountName, signature);
Uri uri = new Uri(FileEndPoint + urlPath);
request = (HttpWebRequest)WebRequest.Create(uri);
if (requestMethod != "Get")
{
    request.ContentLength = data.Length;
}
// string data = "Hello testing";
//int a= ((data.Length) + 1);

request.Method = "PUT";//requestMethod;
request.Headers.Add("x-ms-write", "update");
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", msVersion);
request.Headers.Add("x-ms-range", "bytes=0-65535"); // + ((data.Length) - 1));
request.Headers.Add("Authorization", authorizationHeader);
指导我如何将内容写入azure存储上的简单文件 不使用azure客户端API

为此,您可以直接使用Azure文件存储SDK。我们总是建议使用SDK而不是RESTAPI,因为SDK易于使用

下面是一个使用此SDK的示例

首先,在visual studio中创建.NET framework的控制台项目。然后安装这个nuget包

守则:

using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Auth;
using Microsoft.Azure.Storage.File;
using System;

namespace AzureFileTest2
{
    class Program
    {
        static void Main(string[] args)
        {
            string accountName = "xxx";
            string accountKey = "xxx";
            CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);

            CloudFileClient cloudFileClient = storageAccount.CreateCloudFileClient();

            //make sure the file share named test1 exists.
            CloudFileShare fileShare = cloudFileClient.GetShareReference("test1");
            CloudFileDirectory fileDirectory = fileShare.GetRootDirectoryReference();
            CloudFile myfile = fileDirectory.GetFileReference("test123.txt");

            if (!myfile.Exists())
            {
                //if the file does not exists, then create the file and set the file max size to 100kb.
                myfile.Create(100 * 1024 * 1024);                
            }

            //upload text to the file
            //Besides using UploadText() method to directly upload text, you can also use UploadFromFile() / UploadFromByteArray() / UploadFromStream() methods as per your need.
            myfile.UploadText("hello, it is using azure storage SDK");

            Console.WriteLine("**completed**");
            Console.ReadLine();
        }
    }
}

如果我是你,我会看你的回答。抛出的异常中有一个
HttpWebResponse
,您可以从中检索主体以查看错误响应是什么。或者,使用像Telerik的Fiddler这样的工具来查看请求和错误响应。我得到的响应是:在System.Net.HttpWebRequest.GetResponse()处,在NewFilecreateandupload.Program.UpdateContent(字符串strFileName,字符串内容)在C:\Users\abc\source\repos\NewFilecreateandupload\NewFilecreateandupload\Program.cs:第406行,错误是远程服务器返回了一个错误:(403)禁止。这不是响应主体,这是异常。请参阅AuthenticationFailed服务器无法验证请求。确保包括签名在内的授权标头的值格式正确。RequestId:9917d3cd-f01a-006f-03aa-b400f3000000时间:2019-12-17T07:22:38.8281666Z在HTTP请求“+IN5TBFJHF9BILEYFFDGVIQPIDQ/vrqB+PtDogboY=”中找到的MAC签名与任何计算签名都不同。服务器使用以下字符串签名:“PUT x-ms-date:Tue,2019年12月17日07:22:23 GMT x-ms-range:bytes=0-65535 x-ms-type:file x-ms-version:2015-04-05 x-ms-write:update/bc365storage/lables/rahila.csv comp:range”。我被限制不使用Azure文件存储SDK,我们必须使用rest api使其工作,@RahilaSyed,ok,那么在你的帖子中“或者只是指导我如何在不使用azure客户端API的情况下将内容写入azure存储上的简单文件”是什么意思?我将尝试使用RESTAPI进行此操作,并在稍后更新。@RahilaSyed,请参阅更新部分。如果你还有更多的问题,请告诉我。