Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using WebClient in WCF Service

I am using WebClient to download some resource in following way:

 Stream stream;
 try
 {
  WebClient webClient = new webClient();
  stream = webClient.OpenRead(MyResourceUri);
 }
 catch (Exception)
 {
  return null;
 }
 return stream;

When I do this in a WPF application, it works fine and proper stream is obtained.

When I do this in a WCF service call, it doesn't work. A WebException is thrown with message "Unable to connect to remote server". (It works for files hosted on my machine or within company network, however it fails for any resource on web). The service is hosted on IIS7.

Investigation so far reveals the difference is because of the webproxy. The webclient.proxy in WPF application refers to the proxy settings as set in IE, whereas the one in WCF is having none.

Why is it so? And more importantly, how can I make the WebClient in WCF use similar proxy settings?

EDIT: I set the proxy on WebClient and it worked in WCF service

webClient.Proxy = new WebProxy(ProxyAddressFromIE);

Here I have hardcoded the proxy addess. What method/APIs are there to obtain one? And still why its different in WCF service & in WPF application?

like image 805
Nitesh Avatar asked Jun 07 '11 13:06

Nitesh


2 Answers

To answer one of your questions, the reason there is a difference between your WPF application and your IIS hosted WCF service is this.

WPF applications run in an actual Windows session (your user session to be exact). This means there is a user profile loaded for that session and that session contains, amongst other things, the proxy settings as configured in IE.

WCF services hosted in IIS do not run in a Windows session. They are run as a service and therefor do not have a Windows session (they actually run in session 0, but that's just an implementatio detail). This means there is no proxy configuration.

To reliably solve this, you could have your own configuration for a proxy, perhaps in web.config. Another option is to configure the proxy through netsh.exe.

like image 159
Jonathan van de Veen Avatar answered Oct 06 '22 06:10

Jonathan van de Veen


I needed to do the exact same thing, and I found the answer here: Get the URI from the default web proxy. Basically, you need to dynamically read the proxy using WebRequest.GetSystemWebProxy() and by determining the proxy using a test proxied url.

Hope this helps!

like image 28
mellamokb Avatar answered Oct 06 '22 06:10

mellamokb