c# - 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;
}
}
}
解决方案
除了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;
}
}
推荐阅读
- ios - 如何在 iOS 中忽略来自静态第三方库的警告
- javascript - 参考错误:.match 未定义
- angular - 如何使用 Rollup 在 VS Code 中捆绑由 Angular CLI 创建的 Angular 组件
- jquery - jQuery Ajax GET JSON 数组不返回结果
- laravel - Laravel 护照 GuzzleHttp 错误 API 不是数据
- java - 如何检查是否存在具有动态名称的参数/集合?
- java - QuerydslBinderCustomizer 在 Spring Data JPA 2.0.7 中不起作用
- racket - 在宏中调用其他函数
- netlogo - Netlogo 绘制直方图百分比
- c# - 来自 PostAsync 的 HttpPost 始终为空