In net 4.5 we are working with proxy like this:
<system.net>
<!-- -->
<defaultProxy enabled="true" useDefaultCredentials="false">
<proxy usesystemdefault="True" proxyaddress="http://192.168.1.1:8888" bypassonlocal="True" autoDetect="False" />
<module type="CommonLibrary.Proxy.MyProxy, CommonLibrary, Version=1.0.0.0, Culture=neutral" />
</defaultProxy>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
but in asp.net core or test we can't found a solution like the above
Could someone please help me?
I really appreciate your help
Thanks, Regards
To use an HTTP proxy in .net core, you have to implement IWebProxy
interface.This is from the System.Net.Primitives.dll
assembly. You can add it to project.json
if not already there
e.g.
"frameworks": {
"dotnet4.5": {
"dependencies": {
"System.Net.Primitives": "4.3.0"
}
}
}
Implementation is very trivial
public class MyHttpProxy : IWebProxy
{
public MyHttpProxy()
{
//here you can load it from your custom config settings
this.ProxyUri = new Uri(proxyUri);
}
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;
}
}
var config = new HttpClientHandler
{
UseProxy = true,
Proxy = new MyHttpProxy()
};
//then you can simply pass the config to HttpClient
var http = new HttpClient(config)
checkout https://msdn.microsoft.com/en-us/library/system.net.iwebproxy(v=vs.100).aspx
You should use a middleware. Did you have a look at this one:
https://github.com/aspnet/Proxy
there's a 'samples' folder:
https://github.com/aspnet/Proxy/tree/dev/samples/Microsoft.AspNetCore.Proxy.Samples
Other resources on the topic:
http://josephwoodward.co.uk/2016/07/proxying-http-requests-asp-net-core-using-kestrel
http://overengineer.net/creating-a-simple-proxy-server-middleware-in-asp-net-core
Does a middleware works for you?
Whilst manually setting the proxy works when it's possible to use a HttpClientHander
, defaulting all requests to do so without code, like you could do in the .NET Framework is currently not possible. Which is bummer if you're using a library that doesn't expose this functionality.
The following issue in GitHub is looking at introducing this capability to .NET Core using environment variables: https://github.com/dotnet/corefx/issues/24574
I would recommend anyone who is looking for a solution to follow that issue to check the current implementation state.
Another incompleted work around is:
After you deploy .NET Core app to a web server(mine is IIS). There is actually a web.config file in the root folder.
Manually add
<system.net>
<defaultProxy useDefaultCredentials="true">
</defaultProxy>
</system.net>
or your specific setting will do the magic
Only works on the server though. Your local build still won't work.