向HttpClient添加两个报头

本文关键字:两个 报头 HttpClient 添加 | 更新日期: 2023-09-27 18:08:38

当它只是授权标头时,我让它工作。但是现在我需要添加一个自定义标题。我在tokenResponse中得到一个错误,说"HEADER OUT OF RANGE"。

端点信息:

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

我的代码。

           //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 + "im1@xyz.com";
            string hash = SHA.Generate256string(strToHash);
            //setup the values we need to post
            var values2 = new Dictionary<string, string>();
            values2.Add("email", "im1@xyz.com");
            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...
            }

向HttpClient添加两个报头

当您使用DefaultRequestHeaders并尝试添加自定义标头时,它将尝试对众所周知的标头进行验证,因为您所拥有的是自定义的,它正在失败。
你应该用HttpRequestMessage生成Request
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}"

var response = await httpClient.SendAsync(request);