受欢迎的博客标签

How to use proxy server in asp .net core

Published

Proxy server is use to distribute internet in secure way.  Proxy server acts as an intermediary for requests from clients seeking resources from other servers or Internet. Many organic use proxy server to stop direct access to outside resource .

If  you have application which have a logic to call external API. But due to proxy we can't call API directly. So, We need to enable proxy settings in our application to call external API.

However, there is a small trick here that took me 2 days to solve. It’s not enough just to enable them, but you also have to supply a known proxy IP or known network for it to work as it should. Doing so will prevent IP spoofing attacks.

We have one way to configure proxy in .net application.

1.Setup proxy ip  in appsettings.json

 

2. Use "WebProxy" class for enable proxy

 

The elegant solution is to add a configuration section in appsettings.json with the known proxy IPs:

step 1:add a configuration section in appsettings.json

{
  "KnownProxies": [
    "10.0.0.144"
  ]
}

step 2: use it in ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
   services.Configure(options =>
{
      options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.All;

      foreach (var proxy in Configuration.GetSection("KnownProxies").AsEnumerable().Where(c => c.Value != null))
      {
           options.KnownProxies.Add(IPAddress.Parse(proxy.Value));
      }
});
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseForwardedHeaders();
}

It’s now up to you to determine which is the local proxy IP address to configure correctly