1
votes

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.

1
Why don't you add the header here; var httpRequestMessage = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(service2Address), Content = new StringContent(JsonConvert.SerializeObject(obj)) };Casper Dijkstra
Hi @CasperDijkstra, that makes no difference to the output when add header in initialization of httpRequestMessage or after it.lock norris

1 Answers

0
votes

I have developed code like yours. Have created Two Asp.net core 3.1 project with standart template. One service is starting localhost:44320 and other localhost:44300 localhost:44320/PostService wrote the your codes.

Then get this url with browser. localhost:44320/weatherforecast/IncomeService function is like below

Finally i put breakpoint to where get request header. Result is like below

There is a not a problem. Maybe you use change request header middleware. Or if you are using something like nginx. this problem maybe nginx configuration.