HttpClient POST 请求中的自定义 header 无效

Custom header in HttpClient POST request not working

我试图在使用 HttpClient 时发送 POST 请求。当我 运行 代码时,我收到未经授权的响应。但我能够让它在 PostMan 中工作。下面是我当前的代码片段和我正在尝试执行的图片。我想补充一点,我正在尝试在我的 body.

中发送一个 json 字符串
using (HttpClient client = new HttpClient())
        {
            var connectionUrl = "https://api.accusoft.com/prizmdoc/ViewingSession";
            var content = new Dictionary<string, string> { { "type", "upload" }, { "displayName", "testdoc" } };
            // Serialize our concrete class into a JSON String
            var stringPayload = JsonConvert.SerializeObject(content);

            // Wrap our JSON inside a StringContent which then can be used by the HttpClient class
            var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json");

            using (var httpClient = new HttpClient())
            {
                //client.DefaultRequestHeaders.Add("Acs-Api-Key", "aPsmKCmvkZHf9VakCmfHB8COmzRxXY5FDhj8F1FU1IGmQlOkfjiKESKxfm38lhey");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Acs-Api-Key", "aPsmKCmvkZHf9VakCmfHB8COmzRxXY5FDhj8F1FU1IGmQlOkfjiKESKxfm38lhey");

                // Do the actual request and await the response
                var httpResponse =  httpClient.PostAsync(connectionUrl, httpContent).Result;

                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    // Do something with response. Example get content:
                    var connectionContent = httpResponse.Content.ReadAsStringAsync().Result;

                }
                else
                {
                    // Handle a bad response
                    return;
                }
            }
        }

您正在使用两个 HttpClient,而您只需要使用一个。

using (HttpClient client = new HttpClient())

using (var httpClient = new HttpClient())

第二个 (httpClient) 正在执行 post 但身份验证 header 已添加到 client。只需删除第二个 (httpClient) 并确保使用 client.PostAsync(...) 发送请求。


我也会考虑在发送请求时使用 await,而不是 .Result(查看为什么 here):

var httpResponse = await client.PostAsync(connectionUrl, httpContent);

除了haldo的回答,

在您的代码中,您添加了 Acs-Api-Key header 和 Authorization header,这意味着它最终看起来像 Authorization: Acs-Api-Key (key) 而不是 Acs-Api-Key: (key)是您在 PostMan 中拥有的。

与其将其添加为授权 header,不如将其添加为常规 header。

client.DefaultRequestHeaders.Add("Acs-Api-Key","(key)");

还有其他可能导致问题的原因是您没有像在 PostMan 中那样将内容包装在 "source" object 中。有几种方法可以做到这一点

第一种方法是将其简单地包装成字符串格式:

stringPayload = $"\"source\":{{{stringPayload}}}"

或者您可以在序列化之前通过自己制作 object 而不是字典

var content = new PayloadObject(new Source("upload", "testdoc"));
var stringPayload = JsonConvert.SerializeObject(content);

// Send the request

class PayloadObject{
    Source source {get; set;}
    PayloadObject(Source source){
        this.source = source;
    }
}
class Source{
    string type {get; set;}
    string displayName {get; set;}
    Source(string type, string displayName){
        this.type = type;
        this.displayName = displayName;
    }
}