Reputation: 75
I am developing an application that will be deployed outside of the intranet(proxy server) but I am developing the application behind the proxy server. The proxy server uses http to authenticate and requires a username and password. Is there a way I can use my systems proxy credentials only when running(debugging) the app locally? The app is an ASP core 2.0 app. This is a snippet of a code I use: I want the httpClientHandler used when running debugging only when the application is deployed I don't need this since it's deployed out side of proxy server. How can I achieve this?
await new HttpClient(ProxyConfig.httpClientHandler).SendAsync(request).ConfigureAwait(false);
public class ProxyConfig
{
public static WebProxy proxy = new WebProxy
{
Address = new Uri($"http://***.***.***.com:8080"),
BypassProxyOnLocal = false,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(userName: "****", password: "****")
};
public static HttpClientHandler httpClientHandler = new HttpClientHandler()
{
Proxy = proxy,
};
}
Upvotes: 0
Views: 1249
Reputation: 639
I would suggest to register HttpClient on Startup file and inject it to your Controller or Service.
Checking the environment(IHostingEnvironment), depending on the environment you can register either HttpClient with a proxy handler or without a proxy handler. While you are working locally it should be Development where you can register the HttpClient with a proxy. Otherwise, you will be using the HttpClient instance without a proxy setting.
Here below sample code to register HttpClient:
public class Startup
{
private readonly IHostingEnvironment hostingEnvironment;
public Startup(IHostingEnvironment hostingEnvironment)
{
this.hostingEnvironment = hostingEnvironment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
if(hostingEnvironment.IsDevelopment())
{
var httpClient = new HttpClient(new HttpClientHandler()
{
// Set your proxy details here
});
services.AddSingleton(httpClient);
}
else
{
services.AddSingleton<HttpClient, HttpClient>();
}
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
And sample code to inject HttpClient to your Controller(likewise you can inject it to your Services):
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly HttpClient httpClient;
public ValuesController(HttpClient httpClient)
{
this.httpClient = httpClient;
}
}
Upvotes: 2