我在ASP.NET MVC项目中遇到HttpClient
阻塞问题,它完全拒绝允许Content-Type
标头。我知道技术上它没有任何意义,但对于我所说的API,它是必需的。
curl -X GET \
https://api.sample-service.com/v1/items \
-H 'content-type: application/json' \
-H 'secret-key: sk_test_12345'
他们需要这些标头,如果您退出Content-type
标头,则会返回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请求中包含Content-Type
标头?
答案 0 :(得分:2)
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();