Reputation: 263
I have two WebApi (.NET Core) application e.g. WebApi1 and WebApi2. Now I am calling/consuming WebApi1 (endpoint) from WebApi2. How do I get WebApi1 Http Header values from WebApi2 application?
Tried with Request.Header; but did not get WebApi1 headers. Here is the code written in controller action -
(Request?.Headers ?? throw new Exception("Http Header is Null")).ToDictionary<KeyValuePair<string, StringValues>, string, string>(
header => header.Key, header => header.Value);
here I am getting WebApi2 header.
Upvotes: 0
Views: 1440
Reputation: 263
I missed "Enable CORS" in my application.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com")
**.AllowAnyHeader()**
.AllowAnyMethod();
});
here "AllowAnyHeader" required to pass custom header. Now I am able to capture custom http header.
Upvotes: 0
Reputation: 30056
For calling web api1 from api2, you could try HttpClient
like:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly HttpClient _client;
public ValuesController(IHttpClientFactory httpClientFactory)
{
_client = httpClientFactory.CreateClient();
}
// GET api/values
[HttpGet]
public async Task<ActionResult<IEnumerable<string>>> Get()
{
var response = await _client.GetAsync("https://localhost:44349/api/values");
var headers = response.Headers.ToList();
return new string[] { "value1", "value2" };
}
And register the HttpClient
by
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Upvotes: 1