Skip to content

Can Not Add Header To HttpClient #1618

Open
nanoframework/System.Net.Http
#477
@hamiddd1980

Description

@hamiddd1980

Library/API/IoT binding

nanoFramework.System.Net.Http

Visual Studio version

Microsoft Visual Studio Enterprise 2022 (64-bit) - Preview Version 17.14.0 Preview 2.0

.NET nanoFramework extension version

2022.12.136

Target name(s)

ESP32-S3

Firmware version

No response

Device capabilities

Target capabilities:
Has nanoBooter: NO
IFU capable: NO
Has proprietary bootloader: YES

Description

It is not possible to add Http headers (like User-Agent, Accept) to HttpClient by DefaultRequestHeaders or HttpRequestMessage . Trying to add standard Headers, produces the following exception:
Cannot update restricted header User-Agent.
Cannot update restricted header Accept.

Inspecting the online source code reveals that the problem arises from WebHeaderCollection class in ThrowOnRestrictedHeader method:
the class has a property named HInfo with type of HeaderInfoTable . HeaderInfoTable has a table with predefined Http Headers (Like User-Agent) .
User can not add a Http Header if that header exists in the HeaderInfoTable.
So, how can I add (or change) standard Http Header to httpClient (Like User-Agent,Accept)?

How to reproduce

1.Create a Static HttpClient
httpClient = new HttpClient();
2.Try to Add Headers To DefaultRequestHeaders

httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.5");
 httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:136.0) Gecko/20100101 Firefox/136.0");

Expected behaviour

It should be possible to Add or Change Standard Http Headers to HttpClient

Screenshots

No response

Sample project or code

No response

Aditional information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions