简体   繁体   中英

How can I get a new default WebProxy object in a C# Windows Store app?

My question comes from an issue I discovered on a corporate network. I'm developing with Windows 8 so in my case IE10 is set to automatically detect proxy settings.

In my C# app I use System.Net.Http.HttpClient. I've found that the default IWebProxy object for my entire process becomes unusable if I go offline, make a failed request and then come back online. It's important to make a request that fails, otherwise there is no problem. Here's an example of how I can get an handle on this fragile proxy object.

var defaultHandler = new HttpClientHandler();
var fragileProxy = defaultHandler.Proxy;
var httpClient = new HttpClient(defaultHandler);

After some experimentation I discovered that I could get a working proxy by calling System.Net.WebProxy.GetDefaultProxy();

Then I implemented a NetworkChangAwareProxy : IWebProxy. That's right, a proxy for my IWebProxy. Internally it just goes and gets a new WebProxy.GetDefaultProxy() whenever NetworkChange.NetworkAddressChanged.

I wire it up in when the application starts and the issue goes away.

WebRequest.DefaultWebProxy =  new NetworkChangeAwareProxy();

Hopefully someone will tell me there is a better way to solve this problem. My specific question though is about Application Store Style Apps. (metro apps)

System.Net.WebProxy.GetDefaultProxy() is not available and System.Net.HttpWebRequest.DefaultWebProxy just returns the same defunct proxy after going offline and coming back.

How can I get a handle to a new IWebProxy object in a C# Windows Store app?

System.Net.WebProxy.GetDefaultProxy() has been deprecated since at least .net 3, use System.Net.WebRequest.GetSystemWebProxy() instead. For WinRT, they've removed a lot of deprecated methods.

See http://msdn.microsoft.com/en-us/library/system.net.webproxy.getdefaultproxy.aspx And http://msdn.microsoft.com/en-us/library/system.net.webrequest.getsystemwebproxy.aspx

You can use the web request to get the proxy:

var req = WebRequest.Create(@"api/stat/stats/");
req.Proxy = WebRequest.GetSystemWebProxy();
req.Timeout = 10000;
req.Method = "GET";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM