Skip to content

HttpClient Content-Type Header #60513

Description

@drain

Description

When patching KnownHeaders using reflection and adding the content-type header, another gets added to the request.

Reproduction Steps

After executing this code there will be two content-type headers in the request.

var assembly = typeof(System.Net.Http.Headers.HttpRequestHeaders).Assembly;
var assemblyTypes = assembly.GetTypes();
var knownHeaderType = assemblyTypes.FirstOrDefault(n => n.Name == "KnownHeader");
var headerTypeField = knownHeaderType?
    .GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
    .FirstOrDefault(n => n.Name.Contains("HeaderType"));
if (headerTypeField is null) return;
var headerTypeFieldType = headerTypeField.FieldType;            
var newValue = Enum.Parse(headerTypeFieldType, "All");
var knownHeadersType = assemblyTypes.FirstOrDefault(n => n.Name == "KnownHeaders");
var contentTypeObj = knownHeadersType.GetFields().FirstOrDefault(n => n.Name == "ContentType").GetValue(null);
if (contentTypeObj is null) return;
headerTypeField.SetValue(contentTypeObj, newValue);    
var contentLengthObj = knownHeadersType.GetFields().FirstOrDefault(n => n.Name == "ContentLength").GetValue(null);
if (contentLengthObj is null) return;
headerTypeField.SetValue(contentLengthObj, newValue);

using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://www.example.com/"))
{
    request.Version = new Version(2, 0);
    request.Headers.TryAddWithoutValidation("Content-Type", "application/json; charset=UTF-8");
    request.Headers.TryAddWithoutValidation("content-length", "93");
    request.Headers.TryAddWithoutValidation("accept-encoding", "gzip");
    request.Headers.TryAddWithoutValidation("pragma", "no-cache");
    request.Headers.TryAddWithoutValidation("cache-control", "no-cache");

    request.Content = GetBody();

    var response = await _module.client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

    return await ResponseHandler(response);

} 

Expected behavior

1 content-type header in the request.

Actual behavior

2 content-type headers in the request.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

Why??

Some websites require headers to be sent in a specific order otherwise the request gets rejected. cough akamai

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Net.HttpenhancementProduct code improvement that does NOT require public API changes/additions

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions