Can't set Content-Type header - c#

I'm having trouble setting the Content-Type on HttpClient.
I followed along this question: How do you set the Content-Type header for an HttpClient request?
But still no luck.
String rcString = JsonConvert.SerializeObject(new RoadsmartChecks() { userguid = user_guid, coords = coordinates, radius = (radius * 100) + "" }, ROADSMART_JSON_FORMAT, JSONNET_SETTINGS);
HttpClient c = new HttpClient();
c.BaseAddress = new Uri(BASE_URL);
c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); //Keeps returning false
c.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", hash_aes);
c.DefaultRequestHeaders.TryAddWithoutValidation("Roadsmart-app", Constant.APP_ID);
c.DefaultRequestHeaders.TryAddWithoutValidation("Roadsmart-user", user_guid);
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_CHECKS + "/fetch");
req.Content = new StringContent(rcString);
await c.SendAsync(req).ContinueWith(respTask =>
{
Debug.WriteLine("Response: {0}", respTask.Result);
});
I also tried by using the Flurl library, but it crashes when trying to add the 'Content-Type'.
misused header name content-type
So how can I force it so it really adds it?
Thanks in advance.

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?
Edit
Remove this line c.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json"); and check

UPDATE: See new answer for non-default content types
With Flurl you shouldn't need to set Content-Type to application/json for methods like PostJsonAsync. This is the default content type in this case and it will get set for you.

The latest and greatest answer to this with Flurl is to upgrade. 2.0 introduces several enhancements in the headers dept:
They're no longer validated. Flurl now uses TryAddWithoutValidation under the hood, so you'll never get the "misused header name" error with the WithHeader(s) methods. (I always found that validation behavior to be a bit overprotective.)
In a fluent call they're set at the individual request level rather than the FlurlClient level, so you won't run into concurrency issues when reusing the client.
Since hyphens are common in header names but not allowed in C# identifiers, there's a new convention where underscores are converted to hyphens so you don't have to give up object notation when specifying multiple:
url.WithHeaders(new { Content_Type = "foo", ... }

Related

HttpClient.SendAsync sending wrong Content-Type

HttpClient httpClient = new HttpClient();
MyRequest request = new MyRequest (data);
var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(request), System.Text.Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:8000/api/action"),
Content = content,
Method = HttpMethod.Post
};
httpRequestMessage.SetBrowserRequestMode(BrowserRequestMode.NoCors);
await httpClient.SendAsync(httpRequestMessage);
Using HttpClient in Blazor WebAssembly I am trying to send a request to an API.
However, despite specifying application/json as the content type it sends text/plain;charset=UTF-8 (as viewed in the Chrome Network tab). This results in the API throwing an error.
I think you could check these caseļ¼š
case1,case2
read this document,and try with PostAsJsonAsync method
I tested as below and worked well:
var weatherforecast = new WeatherForecast() { Date = DateTime.Now, Summary = "testsummary", TemperatureC = 44 };
var response = await Http.PostAsJsonAsync("https://localhost:44385/WeatherForecast", weatherforecast);
Result:
Related post:
Wrong Content-Type being substituted for fetch http request
HttpClient in WebAssembly calls the standard fetch method.
As per the fetch specification when using no-cors only a limited number of content-types can be used:
https://fetch.spec.whatwg.org/#simple-header
"application/x-www-form-urlencoded"
"multipart/form-data"
"text/plain"
The preferred solution would be to correctly configure the end point you are calling to allow cross origin requests and not to use no-cors e.g:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
Access-Control-Allow-Origin: *
If this is not possible (as in my case) and you must use no-cors the only other option would be to change your end point to map "text/plain" to "application/json"
Whilst many may not consider this a bug it is an inconsistency in how HttpClient behaves and is not obvious (though the NoCors option is only available in WebAssembly)

Sending custom Content-Type using HttpClient C# .Net6

Hello Stackoverflow community. I hope someone here can help me!!
I'm trying to integrate with the Zoopla API that requires the post request to send the following customized content type. (I've got the certificate side of things working fine).
application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json
I've tried the following approaches without any success (they all result in the following error)
System.FormatException: 'The format of value 'application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json' is invalid.'
Initial approach was to set it within the content of the RequestMessage
var request = new HttpRequestMessage()
{
RequestUri = new Uri("https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list"),
Method = HttpMethod.Post,
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json")
};
When that didn't work I tried to set it via the default headers (the client below is from the ClientFactory)
client.DefaultRequestHeaders.Add("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
My final attempt was to set it without validation
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
I've just tried something else which unfortunately didn't work
string header = "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json";
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(header));
I am well and truly stumped!! HELP!! :-)
Content-Type is set on the content, not in DefaultRequestHeaders. You may try using TryAddWithoutValidation on the request content:
var content = new StringContent("hello");
content.Headers.ContentType = null; // zero out default content type
content.Headers.TryAddWithoutValidation("Content-Type", "application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json");
var client = new HttpClient(); // note: use IHttpClientFactory in non-example code
var response = await client.PostAsync("https://postman-echo.com/post", content);
Console.WriteLine(response.StatusCode); // OK
Console.WriteLine(await response.Content.ReadAsStringAsync());
// {"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-6345b568-22cc353761f361483f2c3157","content-length":"5","content-type":"application/json;profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/list.json"},"json":null,"url":"https://postman-echo.com/post"}

Add content-type header while consuming API using GraphQL.client

I am using GraphQL.client Nuget package to call the Graphql API which requires Content-Type header.
Following is what I am doing
Set GraphQL options. Note I have set options.MediaType
GraphQLHttpClientOptions options = new GraphQLHttpClientOptions();
options.MediaType = "application/json";
options.EndPoint = new Uri( "https://sample.api.com/graphql");
Initialize the client and Authorization header
var graphQLClient = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer());
graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "JWT <token>");
GraphQL query
var projectsQuery = new GraphQLRequest
{
Query = #"
query {
projects {
name
}
}"
};
Invoke the API and retrieve the response results
var graphQLResponse = await graphQLClient.SendQueryAsync<ProjectResponse>(projectsQuery);
var projects = graphQLResponse.Data.Projects;
However I am getting Bad request with error "{"errors":[{"message":"Must provide query string."}]}"
What am I doing wrong here? How do I set the content-type header correctly. I tried adding the content-type header as below but it does not allow giving the
Misused header name. Make sure request headers are used with
HttpRequestMessage, response headers with HttpResponseMessage, and
content headers with HttpContent objects.
graphQLClient.HttpClient.DefaultRequestHeaders.Add("content-type", "application/json");
I tried searching for a solution but did not find one. The same request works when I pass content-type header in the request headers via Postman client.
Does anybody have any pointer on the same?
If anyone is still looking for answer, please find below.
var graphQLClient = new graphQLHttpClient("https://www.example.com/graphql", new NewtonsoftJsonSerializer());
graphQLClient.HttpClient.DefaultRequestHeaders.Add("key", "value");
Please mind the HttpClient in graphQLClient.HttpClient.DefaultRequestHeaders.Add("key", "value");

Unsupported media type in httpclient call c#

I'm a trying to post the following request but I am getting a "Unsupported Media Type" response. I am setting the Content-Type to application/json. Any help would be appreciated. And as per comment below, if i change content as 'new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")' then i get bad request response
string URL = "https://test.com/api/v2/orders/"; //please note it is dummy api endpoint
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(URL),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Bearer ABcdwenlfbl8HY0aGO9Z2NacFj1234" }, //please note it is dummy bearer token
{ HttpRequestHeader.Accept.ToString(), "application/json;indent=2" },
{ HttpRequestHeader.ContentType.ToString(), "application/json" }
},
//Content =new StringContent(JsonConvert.SerializeObject(root), Encoding.UTF8, "application/json")
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
};
var response = client.SendAsync(httpRequestMessage).Result;
With HttpClient, some headers are counted as request headers, and others are counted as content headers. I'm not sure why they made this distinction really, but the bottom line is that you have to add headers in the correct place.
In the case of Content-Type, this can be added as part of the StringContent constructor, or to the constructed StringContent object.
My approach is to use the constructor:
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root), System.Text.Encoding.UTF8, "application/json");
Or alternatively set it afterwards:
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(root))
Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
Note: If your issue still presents after making this change, then it's likely a server-side problem and you'll need to contact the maintainer of the API to ask what you're doing wrong.
I prefer using some third party wrappers like FluentClient
Note that you should not instance a new object for every request, O only did it for the sake of an example.
var client = new FluentClient("https://test.com/api/v2/orders/")
.PostAsync(URI)
.WithBody(root)
.WithBearerAuthentication("ABcdwenlfbl8HY0aGO9Z2NacFj1234");
var response = await client.AsResponse();

How to make GET request in C#, setting Content-Type header & custom header

I am trying to make a GET request in C# and need to set the Content-Type header to application/json and set a header with my api key. I have tried searching but surprisingly have not found a straightforward way to do this.
This answer is very close to what I want, because they are able to set the Content-Type header here, but I also need to set a custom header for my api key and StringContent does not have additional fields for such a thing.
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
^ their answer, for reference.
This is my code, but I get a null result. I know that I can hit the api in postman with these values, but I am assuming the way I configure my HttpRequestMessage is wrong so the request fails.
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Get
};
// need Content to be not null, this seems wrong
request.Content = new StringContent("");
// need to set Content-Type to application/json
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
// set api-key header
request.Content.Headers.Add("api-key", apiAdminKey);
request.RequestUri = new Uri($"{URL}?id={id}");
return client.SendAsync(request, HttpCompletionOption.ResponseContentRead);
Any advice?
Update
Got it working with just HttpClient, for some reason I thought I could not set the headers using client.DefaultRequestHeaders.Add.
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("api-key", apiAdminKey);
return client.GetAsync($"{URL}?id={id}");
Thanks for the help!!!!

Categories

Resources