System.InvalidOperationException:“Misused header name, 'Authorization'. Make sure…
- User
System.InvalidOperationException:“Misused header name, 'Authorization'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.”
- Assistant
This exception is thrown when you are using the 'Authorization' header incorrectly with a request or response in .NET.
To resolve this issue, you need to ensure that you are using the 'Authorization' header correctly in your code. The 'Authorization' header should be used with the
HttpRequestMessagefor request headers,HttpResponseMessagefor response headers, andHttpContentobjects for content headers.Here are a few steps you can follow to resolve this exception:
-
Make sure you are using the correct class for the header you are setting. For example, if you are setting a request header, use
HttpRequestMessage:csharpHttpRequestMessage request = new HttpRequestMessage(); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "your_token");
-
- User
var client = clientFactory.CreateClient(); StringContent content = new StringContent(objPara.ToJson()); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); //var source = HttpContextUtil.Current.Request.Headers["Source"].ToString(); var authCode = token;// HttpContextUtil.Current.Request.Headers["AuthToken"].ToString(); //content.Headers.Add("Source", source); content.Headers.Add("Authorization", authCode); var respMsg = await client.PostAsync(url, content);//url中不能有// string msgBody = await respMsg.Content.ReadAsStringAsync(); return msgBody.ToObject(); 报错System.InvalidOperationException:“Misused header name, 'Authorization'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.” 报错 如何解决
- Assistant
The issue seems to be with the usage of the 'Authorization' header in your code. The 'Authorization' header should be used with the
HttpRequestMessageclass, not withStringContentdirectly.Here's how you can modify your code to set the 'Authorization' header correctly:
csharpvar client = clientFactory.CreateClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url); StringContent content = new StringContent(objPara.ToJson()); content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); var authCode = token; // HttpContextUtil.Current.Request.Headers["AuthToken"].ToString(); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authCode); request.Content = content; var respMsg = await client.SendAsync(request); string msgBody = await respMsg.Content.ReadAsStringAsync(); return msgBody.ToObject<K>();