0

Web API C# .NET Framework 4.7.2

Unfortunately it is not possible to use NET CORE.

I have to do something a lot like:

Configure HttpClientFactory to use data from the current request context

my difference is i can't use NET CORE

To register the dependencies I used Unity.

Global.asax:

protected void Application_Start()
{   
    UnityConfig.RegisterComponents();   
}

UnityConfig.cs

ServiceCollection services = new ServiceCollection();
services.AddHttpClient("MyService",
    client =>
    {
        client.BaseAddress = new Uri(ConfigurationManager.AppSettings["MyServiceBaseUrl"]);
        client.DefaultRequestHeaders.Add("X-IBM-Client-Id", ConfigurationManager.AppSettings["X-IBM-Client-Id"]);
        client.DefaultRequestHeaders.Add("X-IBM-Client-Secret", ConfigurationManager.AppSettings["X-IBM-Client-Secret"]);
    });

the IHttpClientFactory interface and the RestClient object were used to make the Http calls.

Now they are asking me to add a string in the header of each request containing the identity of the logged in user

Since this is the same information for all requests what is the best practice to do this?

Unfortunately I can't do it in UnityConfig.cs as it is called only on application start.

I had two solutions in mind:

try to modify the UnityConfig so that an HttpClient object is instantiated for every single request

or

work on the HttpClient object and possibly extend it to add the desired information in the header.

Fede
  • 9
  • 4
  • What's the problem? HttpClientFactory creates HttpClient instances. It knows nothing about server requests. `client.DefaultRequestHeaders.` only sets the defaults. If you want to use specific headers in a request you can construct an HttpRequestMessage and add the headers you want. – Panagiotis Kanavos Nov 25 '22 at 09:26
  • In my solution I have more than 40 requests. What's the best way to do this without having to repeat the same code? I don't use HttpRequestMessage but RestSharp's RestRequest object – Fede Nov 25 '22 at 09:31

0 Answers0