首页 > 解决方案 > Access x-requestid in HttpResponseMessage

问题描述

Please see the code below:

[HttpPut]
public async Task<IActionResult> CreatePerson([FromBody]CreatePersonCommand command, [FromHeader(Name = "x-requestid")] string requestId)
{
    ..
}

This is a web api method, which is accessed by another project.

The client code looks like this:

var response = await _httpClient.PutAsync(uri, personContent);

Is it possible to access the x-requestid at the client in the response that is sent from the web api project?

标签: c#restasp.net-core

解决方案


If your HttpClient comes from System.Net.Http.

In case you need to get value:

var response = await _httpClient.PutAsync(uri, personContent);

response.Headers.TryGetValues("x-requestid", out var headerValues);

If you need to add headers to the response in your Web API, you have access to Response entity in your controller which inherits from ASP ControllerBase class:

Response.Headers.Add("x-requestid", "value");

推荐阅读