在发送之前检查 HttpRequestMessage

Inspect HttpRequestMessage just before it is sent

我的任务是与 Amazon Gift Codes On Demand (AGCOD) RESTful API. We are required to sign our requests using Signature Version 4, something that is performed by their AWS SDK for .NET 集成其他服务,但不是 AGCOD。

我正在使用HttpClient class from the System.Net.Http namespace to communicate with AWS's API. This in turn is using the HttpClientHandler to create an HttpRequestMessage。在这样做的过程中,额外的 headers 如 HostContent-LengthConnection 被添加到消息中。

我的问题是,在我调用 PostAsync 并添加了 headers 之后,但在它被发送到服务器之前,我该如何检查消息,以便我可以计算和添加签名?

我显然可以自己简单地指定这些 headers。但这仅对已知 headers 有帮助。如果 HttpMessageHandler is used (e.g. the WebRequestHandler) 不同,则可以添加不同的 headers(例如 Content-EncodingCache-Control)。如果我不知道消息中的所有 headers,我将无法计算出正确的签名。

大多数(可能是全部)AWS 服务实际上并不要求您包含所有 header。亚马逊显然预料到这将是有问题的,正是出于您提到的原因。

The canonical headers consist of a list of all the HTTP headers that you are including that are part of the AWS request. As a minimum you must include host header, and different services might require other headers. [emphasis added]

http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html

通常,您需要添加的header是您在应用程序级别已经知道的那些,例如任何service-specificx-amz-* headers。您无需担心包含 header 的示例包括 User-Agent:。 http 客户端库经常添加的 header 是 Date: header,但是如果您包含具有相同日期的 properly-formatted x-amz-date: header您用于计算签名,实际的 Date: header 将在验证签名时被忽略,并且将使用您的替代。

我知道这并没有直接回答你的问题,但我怀疑你预期需要做的事情可能很乏味或不切实际,所以我认为这个信息值得一提。