首页 > 解决方案 > 使用承载身份验证时未发送正文

问题描述

我有一个 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但我想这是一种简单的格式选择,在使用身份验证时似乎不是必需的。

我在用着:

还尝试了使用 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;
  }
}

标签: c#posthttpclient

解决方案


您的不记名令牌(传递给 SetToken 方法的字符串)是否包含换行符?这可能会导致该问题。


推荐阅读