首页 > 解决方案 > HttpClient POST 请求中的自定义标头不起作用

问题描述

我在使用 HttpClient 时尝试发送 POST 请求。当我运行代码时,我得到了未经授权的响应。但我可以让它在 PostMan 中工作。下面是我当前的代码片段和我正在尝试执行的图片。我想补充一下,我正在尝试在我的身体中发送一个 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;
                }
            }
        }

PostMan 标头段

邮递员身体部位

标签: c#httpwebrequesthttpclient

解决方案


除了haldo的回答,

在您的代码中,您将Acs-Api-Key标题添加为Authorization header,这意味着它最终看起来像Authorization: Acs-Api-Key (key)而不是Acs-Api-Key: (key)PostMan 中的内容。

不要将其添加为授权标头,只需将其添加为常规标头即可。

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

其他可能导致问题的事情是您没有像在 PostMan 中那样将内容包装在“源”对象中。有几种方法可以做到这一点

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

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

或者您可以在序列化之前通过制作自己的对象而不是 Dictionary

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;
    }
}

推荐阅读