Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding HttpClient headers generates a FormatException with some values

This occurred within the context of coding against Google Cloud Messaging, but applies elsewhere.

Consider the following:

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

and

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

both of which generate a FormatException:

System.FormatException : The format of value key=XXX' is invalid.

The solution is to remove the equals sign.

  1. Digging into reflector shows there is oodles of validation and parsing code that runs when adding a a new header value. Why is all this necessary? Shouldn't this client just be getting out of our way?

  2. How do you escape the equals sign so that adding this value succeeds?

like image 508
Andrew Avatar asked Nov 02 '12 15:11

Andrew


3 Answers

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");
like image 65
Antonio Avatar answered Nov 02 '22 05:11

Antonio


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.

like image 32
Terry Chang Avatar answered Nov 02 '22 06:11

Terry Chang


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...

like image 10
Robert Stokes Avatar answered Nov 02 '22 06:11

Robert Stokes