Remove content-type media type if cURL doesn't include it
guitarrapc opened this issue · 2 comments
TL;DR
To Respect cURL's content-type, reset StringContent's ContentType Header when cURL not using Content-Type media-type.
What will happen
Some kind of services are checking Content-Type with ==
, not allow adding media-type, cURL will be success but generated C# Code will fail.
I was met this issue with Kubernetes Agones service.
Reproduce
use default POST JSON
curl command and generated C# Code.
curl https://sentry.io/api/0/projects/1/groups/?status=unresolved -d '{"status": "resolved"}' -H 'Content-Type: application/json' -u 'username:password' -H 'Accept: application/json' -H 'User-Agent: curl/7.60.0'
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://sentry.io/api/0/projects/1/groups/?status=unresolved"))
{
request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Headers.TryAddWithoutValidation("User-Agent", "curl/7.60.0");
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{\"status\": \"resolved\"}", Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
response.Dump();
}
}
send it to httpbin running on docker.
docker run -p 8080:80 kennethreitz/httpbin
check response's RequestMessage > Content > Headers > Content-Type.
You will find ; charset=utf-8
was automatically added.
Reason
StringContent will automatically add media-type even if you set null
for encoding.
new StringContent("{\"key\":\"value\"}", null, "application/json");
Suggestion Fix
Set StringContet's ContentType after constructor.
var c = new StringContent("{\"status\": \"resolved\"}", Encoding.UTF8, "application/json");
c.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
request.Content = c;
thank you, confirm deployed and works fine.
Thank you for the contribution 👍