Adding HttpClient headers generates a FormatException with some values

I ran into this error and stumbled on to this post when I added a space to the end of an Authorization header.

this.bearerAuthHttpClient.DefaultRequestHeaders.Add("Authorization ", $"Bearer {token}");

You can see the offending " " after Authorization.

It took me about 15 min before I saw my typo...


I got around this exception (my FormatException caused by commas in the value) by setting the Authorization header in the following way:

var authenticationHeaderValue = new AuthenticationHeaderValue("some scheme", "some value");
client.DefaultRequestHeaders.Authorization = authenticationHeaderValue;

To your "why is all this (parsing and validation) necessary" question, the answer is: it is defined in the HTTP standard.

In HTTP/1.1 and RFC2617, the value an authentication header (such as WWW-Authenticate and Authorization) has two parts: a scheme part, and a parameter part.

For HTTP Basic Authentication, the scheme is "Basic", and the parameter may be something like "QWxhZGRpbjpvcGVuIHNlc2FtZQ==", so the whole header becomes:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

That's why your "key=XXX" doesn't pass validation, because it lacks a scheme part.


Not sure if still relevant, but I recently ran into this same issue and was able to solve it by calling a different method to add the header information:

var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");