0

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.

8
  • Can you also provide the code you tried to get the header ? Not just the Request.Header instruction, the relevant parts of the method. Commented May 23, 2019 at 11:54
  • @Skrface - code added Commented May 23, 2019 at 12:20
  • Are you sure you actually send any headers? Commented May 23, 2019 at 12:29
  • Yes I am sending from WebApi1, from Fiddler I verified. Commented May 23, 2019 at 12:31
  • @DebasisGhosh Request.Headers.GetValues(string name)? Commented May 23, 2019 at 12:33

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.