I have several RESTful services that working with each other. In one scenario I want to post some data from one service to another service and I want to attach some information in Header of the request. I saw several cases to do this and in the end I came up with this workaround:
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();
With these lines of code, a Post
request sent, but in service2
when I want to get the headers from request, there is no sign of myCustomHeaderKey
in headers collection. I inspect Request.Headers
in Visual Studio Watch and even try to get custom header with Request.Headers["myCustomHeaderKey"]
. So what's wrong here?
EDIT 1
This implementation in based on this tutorial.
var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(service2Address), Content = new StringContent(JsonConvert.SerializeObject(obj)) };
– Casper DijkstrahttpRequestMessage
or after it. – lock norris