HttpClient POST请求中的自定义标头不起作用

时间:2020-01-27 15:32:54

标签: c# httpwebrequest httpclient

我正在尝试使用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 Header Segment

PostMan Body Segment

2 个答案:

答案 0 :(得分:1)

您只需要使用两个HttpClient

using (HttpClient client = new HttpClient())

using (var httpClient = new HttpClient())

第二个(httpClient)正在发布,但是身份验证标头已添加到client。只需删除第二个(httpClient)并确保使用client.PostAsync(...)发送请求即可。


在发送请求时,我还会考虑使用await而不是.Result(请参阅here的原因)

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

答案 1 :(得分:1)

除了haldo的答案,

在您的代码中,您将Acs-Api-Key标头添加为Authorization header和{{3}},这意味着它最终看起来像Authorization: Acs-Api-Key (key)而不是Acs-Api-Key: (key)

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

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

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

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

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

或者您可以在序列化之前通过制作自己的对象而不使用字典来做到这一点

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;
    }
}
相关问题