c# - 使用承载身份验证时未发送正文
问题描述
我有一个 winform 客户端,它使用 Zalando 的 Connexion 和 OpenAPI 3 使用来自 Python Flask API 的数据。客户端使用 Net Framework 4.8。当我发送带有 Authorization 标头的 POST 请求时,没有发送正文,因此我从服务器收到错误 400。我已经在 API 端检查了接收到的数据,我还用 Flask 创建了一个空白项目,它只输出它作为请求接收到的内容,而正文不存在。检查 Visual Studio 上的内容会显示正文,但它永远不会到达 API 服务器。如果我不放置授权标头,它可以正常工作。它也适用于 GET,带有标题。这就是我在客户端设置令牌的方式:
public void SetToken(string token) {
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
}
这是我的客户端默认构造函数:
public class RestClient{
private readonly HttpClient Client;
public RestClient {
Client = new HttpClient();
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
在向有同样问题的人询问之前,我已经搜索了很多,但找不到任何帖子。我还看到几乎所有示例都form/urlencoded
用于 POST 而不是,application/json
但我想这是一种简单的格式选择,在使用身份验证时似乎不是必需的。
我在用着:
- 视觉工作室 2019
- Net Framework 4.8(也尝试使用 4.7)
- Python 3.7.2
- 烧瓶 1.1.1
- 连接 2.3.0
还尝试了使用 requests 库在 Python 上创建了承载授权的 API 测试套件,并且从那里可以正常工作...
编辑:根据要求添加我的邮政编码:
public HttpResponseMessage Post(string path, HttpContent content, int maxRetries = 0)
{
if (maxRetries < 0)
{
throw new ArgumentException("maxRetries cannot be less than 0");
}
int attemptsMade = 0;
int maxAttempts = maxRetries + 1;
bool workCompletedSuccessfully = false;
bool attemptsRemain = true;
HttpResponseMessage response = null;
while (!workCompletedSuccessfully && attemptsRemain)
{
attemptsMade++;
attemptsRemain = attemptsMade < maxAttempts;
try
{
response = Client.PostAsync(path, content).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
workCompletedSuccessfully = true;
}
}
catch (Exception e)
{
if (!attemptsRemain)
{
throw e;
}
}
}
return response;
}
这就是我从服务中调用它的方式:
private const string PATH = "person";
public PersonService(RestClient rest)
{
_rest = rest;
}
public HttpResponseMessage AddNew(Person person)
{
var personJson = JsonConvert.SerializeObject(person);
using (var content = new StringContent(personJson, Encoding.UTF8, "application/json"))
{
var result = _rest.Post($"api/{PATH}", content);
return result;
}
}
解决方案
您的不记名令牌(传递给 SetToken 方法的字符串)是否包含换行符?这可能会导致该问题。
推荐阅读
- javascript - Django-Ajax:使用包含文件字段的 AJAX 提交表单,给我 500 错误:“FieldFile”类型的对象不是 JSON 可序列化的
- python - 如何使用 iterrows 和 iteritems 更快地运行这个 pandas for 循环
- javascript - 具有固定列的响应式水平滚动表
- sql - 对 Vertica 中的查询的 OFFSET 影响
- node.js - nodemon自动重新加载不适用于docker
- colors - 不同颜色图像的 Openlayer 聚类
- vba - 使用 vba 上的选项卡拆分文本
- javascript - javascript中特定字符的密码验证
- r - Shiny中基于用户输入的条件过滤
- ruby-on-rails - rails-settings 获取键的所有设置