Search code examples
c#dotnet-httpclient

C# Addin a value with a colon to an HTTPRequestMessage


Hi First fo all there have been several questions much similar to this. But none of them had a straight working answer. So I leave it here in case some one can help me.

I need to add a header to an HTTP Request in C# with a value that contains a colon. Something like 23:token.

The way I do this is by doing either:

string auth_string = this.user + ":" + this.token;
client.DefaultRequestHeaders.Add("Authorization",Uri.EscapeDataString(auth_string));

Or using the auth string like so:

requestMessage.Headers.Add("Authorization", Uri.EscapeDataString(auth_string));

Both of these methods throw the same error when NOT using Uri.EscapedDataString:

System.FormatException: the value is invalid

So this question has been asked here:

HttpRequestMessage UserAgent with Colon

Where the suggestion is to use Uri.EscapedDataString. This works but the colon is replaced by a % which makes it so that the API cannot split the value by the colon, as it does not exist.

The other question that I found: System.FormatException when adding User-Agent with colon

Where the answer basically suggests doing what I'm already doing. The OP says this doesn't work, but when the answerer ask for more info, the OP never answered again.

So I'm asking here, how can I send the value with the colon?


Solution

  • You can use TryAddWithoutValidation - this skips the checks.