How can I send Content-Type header with a GET requ

2019-02-27 09:50发布

问题:

I'm having a blocking issue with HttpClient in an ASP.NET MVC project where it completely refuses to allow the Content-Type header. I know that technically it has no meaning, but for the API I'm calling, it's required.

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

They require these headers and if you leave the Content-type header out, it will return a BadRequest. I do not have control over this.

I managed to get this working in .NET Core 2, but it's completely denied in MVC. Here's a sample of the code:

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

The above works in .Net Core but not MVC. It throws a ProtocolViolationException.

What can I do in MVC to force-include the Content-Type header in GET requests?

回答1:

content-type is set as an attribute of HttpWebRequest in MVC

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

This is how I usually do Web requests in MVC

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