How do you set the Content-Type header for an HttpClient request?
The content type is a header of the content, not of the request, which is why this is failing. AddWithoutValidation
as suggested by Robert Levy may work, but you can also set the content type when creating the request content itself (note that the code snippet adds application/json
in two places-for Accept and Content-Type headers):
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://example.com/");
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
client.SendAsync(request)
.ContinueWith(responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
});
How can I add Content-Type to header of http post method?
You could refer the following sample to set the Content-Type:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44310/api/todo/"); //Change the Uri and request content to yours.
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
await client.SendAsync(request)
.ContinueWith(async responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
var Content = await responseTask.Result.Content.ReadAsStringAsync();
});
And the web API method like this:
[HttpPost]
[Route("relativeAddress")]
public string GetAddress([FromBody]TestUserViewModel testUser)
{
return "Address A";
}
View Model:
public class TestUserViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}
The result as below:
Explicitly Set Content-Type Headers For Get Operation in HttpClient
Based on my findings i concluded the HttpClient is very restrictive in terms of the protocol rules. I also reflected through the implementation DLL and i couldn't find anything that it would indicate that it allows protocol violations.
GET requests shouldn't have content-type headers, and the HttpClient is enforcing that rule.
I think the exception message when you try to set the content-type header is self-descriptive:
System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.
Also if you use set the content body you get one more self-descriptive message:
System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
Since you are willing to violate HTTP rules for GET requests i am pretty sure your only option is to stick with the less restrictive WebClient, which works in that scenario.
Can't set Content-Type header
I think you should try this
req.Content = new StringContent(rcString, Encoding.UTF8, "application/json");
checkout this links :
How do you set the Content-Type header for an HttpClient request?
EditRemove this line c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
and check
Related Topics
Client Specific Role Based Authentication
How to Secure the Asp.Net_Sessionid Cookie
Getting the Latest File Modified from Azure Blob
How to Perform Join Between Multiple Tables in Linq Lambda
Passing a List of Objects into an MVC Controller Method Using Jquery Ajax
How to Check for a Valid Base64 Encoded String
How to Get User Browser Name ( User-Agent ) in ASP.NET Core
How to Wait Until Task Is Finished in C#
How to Fix Json.Net (Newtonsoft.Json) Runtime File Load Exception
Pass Variable in Json String in C#
Trying to Add Spaces Between Characters in a String in C#
Access Variables/Functions from Another Component
Copy Files With Authentication in C#
Asp.Net Core - Swashbuckle Not Creating Swagger.Json File
How to Open in Default Browser in C#
How to Add/Update Child Entities When Updating a Parent Entity in Ef
How to Get the Specific Column in Excel Worksheet Using Documentformat.Openxml C#