400(未指定此请求必需的 HTTP 标头。 尝试在 C# 中上传到 Azure 时

  • 本文关键字:Azure 请求 未指定 标头 HTTP c# azure rest
  • 更新时间 :
  • 英文 :


我试图从c#上传一个简单的空。txt到Azure blob存储(目前只是一个概念证明)。我正在使用SAS令牌(它适用于我迄今为止尝试过的所有其他情况,例如列出容器或删除blob)。但是当尝试创建一个新的blob时,我得到的错误是400(没有指定此请求的强制HTTP头)我想我以错误的方式配置了请求,但我找不到正确的方式。有人能帮忙吗?Put Rest API调用可以在这里找到。

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Xml.Linq;

namespace ConsoleProgram
{
public class Class1
{
private static string URL = "https://example.blob.core.windows.net/";
private static string sasToken = "sv=2019-12-12&ss=b&srt=sco&sp=rwdlacx&se=2021-02-02T15:52:32Z&st=2021-02-02T07:52:32Z&spr=https&sig=realSig";
private static string command =  "";
private static string commandType = "Put";

static void PutBlob()
{
URL = "https://example.blob.core.windows.net/test/hello2.txt";
command = "?";
commandType = "Put";
}
static void ListContainers()
{
URL = "https://example.blob.core.windows.net/";
command = "?comp=list&";
commandType = "Get";
}
static void ListBlobs()
{
URL = "https://example.blob.core.windows.net/test";
command = "?restype=container&comp=list&";
commandType = "Get";
}
static void DeleteBlob()
{
URL = "https://example.blob.core.windows.net/test/hello2.txt";
command = "?";
commandType = "Delete";
}
static void Main(string[] args)
{
PutBlob();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
// List data response.
if (commandType == "Get")
{
response = client.GetAsync(command + sasToken).Result;  // Blocking call! Program will wait here until a response is received or a timeout occurs.
}
else if (commandType == "Delete")
{
response = client.DeleteAsync(command + sasToken).Result;
}
else
{
// This is the Code that causes the problems
var s=new StringContent("hello2.txt");
response = client.PutAsync(command+sasToken,s).Result;
}
if (response.IsSuccessStatusCode)
{
Console.WriteLine("---------------Positive Responce----------------");
Console.WriteLine(response.ToString());
// Parse the response body.
var dataObjects = response.Content.ReadAsStringAsync().Result;  //Make sure to add a reference to System.Net.Http.Formatting.dll
}
else
{
Console.WriteLine("---------------Negative Responce----------------");
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
// Make any other calls using HttpClient here.
// Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
client.Dispose();
}

}
}

简单添加一行:

client.DefaultRequestHeaders.Add("x-ms-blob-type", "BlockBlob");

为我修复。