Matt Winer
Matt Winer

Reputation: 535

adding two headers to HttpClient

I had this working when it was just the authorization header. But now that I needed to add a custom header. I get an error in the tokenResponse that says "HEADER OUT OF RANGE".

Here's the endpoint information:

URI: https://api.xyzcompany.com/api/v10/proxyUserToken
METHOD: POST
Params: email
Required headers: X-iMem-Date, Authorization

My Code.

           //get current date and time 
           DateTime dt = DateTime.Now;
            string date = string.Format("{0:ddd}, {0: dd MMM yyyy HH:mm:ss} GMT", dt);

           //hash together for header
            string strToHash = secret + date + "[email protected]";
            string hash = SHA.Generate256string(strToHash);

            //setup the values we need to post
            var values2 = new Dictionary<string, string>();
            values2.Add("email", "[email protected]");
            var content2 = new FormUrlEncodedContent(values2);

            //setup the auth header
            string auth = string.Format("IMEM {0}:{1}", token, hash);

            //setup client and add the headers
            HttpClient client2 = new HttpClient();
            client2.BaseAddress = new Uri(postURL);
            client2.DefaultRequestHeaders.Add("X-iMem-Date", date);
            client2.DefaultRequestHeaders.Add("Authorization", auth);

            //post and get responses
            HttpResponseMessage response2 = await client2.PostAsync(new Uri(postURL), content2);
            var tokenresponse = await response2.Content.ReadAsStringAsync();
            if (response2.IsSuccessStatusCode)
            {
                ...do stuff...
            }

Upvotes: 1

Views: 10071

Answers (1)

Vignesh.N
Vignesh.N

Reputation: 2666

When you use DefaultRequestHeaders and try to add a custom header, it will try to validate against well-known headers, since what you have is custom it is failing.
You should form the Request using HttpRequestMessage
https://msdn.microsoft.com/en-us/library/system.net.http.headers.httprequestheaders(v=vs.118).aspx

var request = new HttpRequestMessage(HttpMethod.Post, new Uri(requestUrl));
request.Headers.Add("Your-Custom-Header", "Value");
request.Content = "{your request content}"

and then

var response = await httpClient.SendAsync(request);

Upvotes: 5

Related Questions