Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request headers must contain only ASCII characters while using c# http client?

I am using HttpClient to make a POST call by passing header but at some point of time I am getting an error as:

Request headers must contain only ASCII characters.

With stacktrace as:

at System.Net.Http.HttpConnection.WriteStringAsync(String s)
   at System.Net.Http.HttpConnection.WriteHeadersAsync(HttpHeaders headers, String cookiesFromContainer)
   at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithNtConnectionAuthAsync(HttpConnection connection, HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)

Here is my code:

public HttpWrapper(string endpoint, Func<IDictionary<string, string>> NewHeader)
{
    _httpClient = new HttpClient();
    _httpClient.BaseAddress = new Uri(endpoint);

    if (NewHeader != null)
    {
        var headers = NewHeader();
        foreach (var header in headers)
        {
            _httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
        }
    }
}

Do I need to do something with header.Value to fix this issue? I was reading online so looks like I need to use Utf-8 here but not sure on how to do it properly?

Update

I got header value like this today and it threw same exception since HttpUtility.HtmlEncode didn't do anything on it. Also I am not sure what is this character <0x94>? Any thoughts why it is happening?

Also I am not sure

enter image description here

like image 867
AndyP Avatar asked Nov 11 '20 18:11

AndyP


People also ask

What a request header must contain?

HTTP headers let the client and the server pass additional information with an HTTP request or response. An HTTP header consists of its case-insensitive name followed by a colon ( : ), then by its value. Whitespace before the value is ignored.

What is a non ASCII character?

Non-ASCII characters are those that are not encoded in ASCII, such as Unicode, EBCDIC, etc. ASCII is limited to 128 characters and was initially developed for the English language.

Is ASCII a character?

ASCII is a 7-bit character set containing 128 characters. It contains the numbers from 0-9, the upper and lower case English letters from A to Z, and some special characters. The character sets used in modern computers, in HTML, and on the Internet, are all based on ASCII.

What are Httpheaders?

An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.


2 Answers

You can try to encode header values to HTML:

_httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, HttpUtility.HtmlEncode(header.Value));

Your string, Ergänzendes will be "Erg&#228;nzendes".

like image 164
Yigit Yuksel Avatar answered Nov 07 '22 10:11

Yigit Yuksel


I hope this may help in your specific scenario or others with a similar situation. In my case, my header was containing non ASCII characters as one of the Headers values was generated by creating a sha256 HMAC. That was a requirement from the service I was trying to send my request. So, what I had to do in order to encode those characters into ASCII was just this:

//hashedSignature is the one containing NON ASCII charcters!
string MessageSignatureValue = System.Text.Encoding.ASCII.GetString(hashedSignature); 
httpClient.DefaultRequestHeaders.Add(MessageSignaturField, MessageSignatureValue);

I have just included the importants pieces of code.

So, System.Text.Encoding.ASCII.GetString() method did the trick!

Again, I hope it helps.

like image 37
Sebastian Inones Avatar answered Nov 07 '22 11:11

Sebastian Inones