11

When I try to make a GET request with the address and Authorization value below, I have no problems.

Address: http://example.com/xyz.svc/branches/?latitude=0&longitude=0&range=20000

Header Key: Authorization

Value: example;foo

When I try it with HttpCLient I get format invalid error for the authorization header value

This is how I tried

HttpClient client = new HttpClient();

    string latitude = "0";
    string longitude = "0";
    string range = "2000";

    string uri = "/xyz.svc/branches/?latitude=0&longitude=0&range=20000;

    string value = "foo";

    client.BaseAddress = new Uri("http://example.com");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", String.Format("example;{0}", value));

    HttpResponseMessage response = await client.GetAsync(uri);

    var responseJson = await response.Content.ReadAsStringAsync();

    Console.WriteLine(responseJson);

What am I doing wrong?

3
  • What happens if you supply the authorization like this? It's how i do it: client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("example;foo")));
    – Niklas
    Apr 13, 2018 at 14:15
  • Its : not ; btw.
    – Alex K.
    Apr 13, 2018 at 14:24
  • @Alex K, if you are referring to Authorization Value it is ; in my case. It's in a string
    – Ege Bayrak
    Apr 13, 2018 at 14:27

1 Answer 1

24

Normally that authorization header has a format as {scheme} {token} which is what it is trying to validate with your current code.

Some servers can be configured to accept different formats. To avoid the client validating the standard format use TryAddWithoutValidation

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", String.Format("example;{0}", value));

which based on your example would have the following request headers

Accept application/json
Authorization example;foo
2
  • 2
    For anyone trying to use google's format of key=blahblahblahblah this works perfect! Oct 4, 2018 at 19:05
  • Thank you sweet jesus. I can't tell you how annoying the validation is, I interact with services all the time that require the format, "Authorization: code" with no realm.
    – Watson
    Aug 31, 2020 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.