如何在 ASP.NET MVC 中使用 GET 请求发送 Content-Type header?

How can I send Content-Type header with a GET request in ASP.NET MVC?

我在 ASP.NET MVC 项目中遇到 HttpClient 的阻塞问题,它完全拒绝允许 Content-Type header。我知道从技术上讲它没有任何意义,但对于我正在呼叫的 API,它是必需的。

curl -X GET \
  https://api.sample-service.com/v1/items \
  -H 'content-type: application/json' \
  -H 'secret-key: sk_test_12345'

他们需要这些 header,如果您将 Content-type header 留在外面,它将 return 一个 BadRequest。我无法控制这个。

我设法让它在 .NET Core 2 中工作,但它在 MVC 中被完全拒绝。这是代码示例:

var client = new HttpClient
{
   BaseAddress = new Uri("https://api.sample-service.com/v1/")
};

client.DefaultRequestHeaders.Add("secret-key", "my-secret-key");

var content = new StreamContent(Stream.Null);
content.Headers.Add("Content-Type", "application/json");

var request = new HttpRequestMessage(HttpMethod.Get, "items")
{
   Content = content
};

var response = await client.SendAsync(request);

以上适用于 .Net Core 但不适用于 MVC。它抛出 ProtocolViolationException

我可以在 MVC 中对 GET 请求中的 force-include Content-Type header 做些什么?

content-type 在 MVC 中设置为 HttpWebRequest 的一个属性

var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);   //URL is a string with your url
httpWebRequest.ContentType = "application/json";

这就是我通常在 MVC 中进行 Web 请求的方式

string URL = ""; //your url
if (URL.Contains("https"))
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                ServicePointManager.ServerCertificateValidationCallback = (RemoteCertificateValidationCallback)Delegate.Combine(ServicePointManager.ServerCertificateValidationCallback, new RemoteCertificateValidationCallback((object s, X509Certificate ce, X509Chain ch, SslPolicyErrors tls) => true));
            }
CookieContainer cookieJar = new CookieContainer();
var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);   
string petition = ""; //leave empty for get requests  
string result = ""; //if the server answers it will do so here
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
httpWebRequest.Headers["Authorization"] = "passkeydlkefjswlkejcvekexample"; //this is how you add custom headers, you can change it to anything
var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());


                streamWriter.Write(Petition);
                streamWriter.Flush();
                streamWriter.Close();


            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            var streamReader = new StreamReader(httpResponse.GetResponseStream());

            result = streamReader.ReadToEnd();