【问题标题】:NetCore 3.1 PostAsync CustomHeaders not workingNet Core 3.1 PostAsync 自定义标头不起作用
【发布时间】:2020-10-24 10:26:50
【问题描述】:

我有几个相互协作的 RESTful 服务。在一种情况下,我想将一些数据从一个服务发布到另一个服务,并且我想在请求的 Header 中附加一些信息。我看到了几个这样做的案例,最后我想出了这个解决方法:

var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(3);
var httpRequestMessage = new HttpRequestMessage {
    Method = HttpMethod.Post,
    RequestUri = new Uri(service2Address),
    Content = new StringContent(JsonConvert.SerializeObject(obj))
};

httpRequestMessage.Headers.Add("myCustomHeaderKey", "myCustomHeaderValue");

var response = await httpClient.SendAsync(httpRequestMessage);

var responseString = await response.Content.ReadAsStringAsync();

通过这些代码行,发送了Post 请求,但是在service2 中,当我想从请求中获取标头时,标头集合中没有myCustomHeaderKey 的迹象。我在 Visual Studio Watch 中检查Request.Headers,甚至尝试使用Request.Headers["myCustomHeaderKey"] 获取自定义标头。那么这里有什么问题呢?

编辑 1
此实现基于此tutorial

【问题讨论】:

  • 为什么不在这里添加标题; var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(service2Address), Content = new StringContent(JsonConvert.SerializeObject(obj)) };
  • 嗨@CasperDijkstra,在httpRequestMessage 的初始化中或之后添加标题对输出没有影响。

标签: asp.net-core .net-core asp.net-core-webapi


【解决方案1】:

我已经开发了和你一样的代码。使用标准模板创建了两个 Asp.net core 3.1 项目。一项服务正在启动 localhost:44320 和其他 localhost:44300 localhost:44320/PostService 编写了你的​​代码。

然后用浏览器获取这个 url。 localhost:44320/weatherforecast/IncomeService 函数如下所示

最后我把断点放在获取请求头的位置。结果如下所示

没有问题。也许您使用更改请求标头中间件。或者,如果您使用的是 nginx 之类的东西。这个问题可能是nginx配置。

【讨论】:

    猜你喜欢
    • 2021-06-17
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2021-08-10
    • 2020-07-25
    • 1970-01-01
    相关资源
    最近更新 更多