Skip to content

Instantly share code, notes, and snippets.

@bgavrilMS
Last active June 18, 2018 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgavrilMS/29dcaf7e97d15570a89e7e113765d5bc to your computer and use it in GitHub Desktop.
Save bgavrilMS/29dcaf7e97d15570a89e7e113765d5bc to your computer and use it in GitHub Desktop.
Use of proxy in dot net core
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
MainAsync().Wait();
Console.WriteLine("Hello World!");
}
static async Task MainAsync()
{
string page = "http://en.wikipedia.org/";
HttpClientHandler httpClientHandler = new HttpClientHandler()
{
UseDefaultCredentials = true,
UseProxy = true,
Proxy = new MyHttpProxy()
};
// ... Use HttpClient.
using (HttpClient client = new HttpClient(httpClientHandler))
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null &&
result.Length >= 50)
{
Console.WriteLine(result.Substring(0, 50) + "...");
}
}
}
}
public class MyHttpProxy : IWebProxy
{
public MyHttpProxy()
{
//here you can load it from your custom config settings
this.ProxyUri = new Uri("http://127.0.0.1:8888");
}
public Uri ProxyUri { get; set; }
public ICredentials Credentials { get; set; }
public Uri GetProxy(Uri destination)
{
return this.ProxyUri;
}
public bool IsBypassed(Uri host)
{
//you can proxy all requests or implement bypass urls based on config settings
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment