Home > Back-end >  Set Application level proxy in .Net 5.0 project
Set Application level proxy in .Net 5.0 project

Time:10-06

I have to set a proxy for the .net 5.0 application. I referred https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.defaultproxy?view=net-5.0 which mentioned I can set HTTP_PROXY environment variable, which will be used for all the calls. Another option is I use HttpClientHandler to set the proxy for every client.

Is there a way I can set the proxy at the application level so that other applications don't get affected(this might happen in the case of setting the env variable)? And I don't want to set proxy at individual client level(HttpClient, SecretClient, etc).

CodePudding user response:

Environment variables are not necessarily system-wide.

To state from Wikipedia, "In all Unix and Unix-like systems, as well as on Windows, each process has its own separate set of environment variables. By default, when a process is created, it inherits a duplicate run-time environment of its parent process".

If you don't set variables system-wide, the environment variables will stay in that process and its children.

Launching applications in the same process or child process would lead to the problem you described, but when you use different processes you should be fine.

This can also be used with Dockerfiles if you are still worried about interference.

CodePudding user response:

This worked for all clients(httpclient and SecretClient), at the process level.

 HttpClientHandler handler = new HttpClientHandler();
 handler.Proxy = new WebProxy("Proxyaddress:proxyPort", true);
 Environment.SetEnvironmentVariable("HTTP_PROXY", "Proxyaddress:proxyPort");
 Environment.SetEnvironmentVariable("HTTPS_PROXY", "Proxyaddress:proxyPort");
  • Related