asp.net core defaultProxy

拜拜、爱过 提交于 2019-11-28 20:51:38
Rohith

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

Adrian

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.

Thankfully, from .NET Core 3.0, this will be possible simply by setting environment variables (i.e. behaves exactly as Linux has worked forever): https://github.com/dotnet/corefx/issues/37187

Alternatively, https://github.com/dotnet/corefx/issues/36553 added a new static DefaultWebProxy property on HttpClient that will allow you to accomplish the same thing via code. This will also be available in Core 3.0.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!