How to use proxy server in .net application

 

Keywords - How to use proxy server in .net application, use proxy in .net application, configuration of proxy in asp.net 

Proxy server is use to distribute internet in secure way.  Proxy server acts as an intermediary for requests from clients seeking resources from other servers or Internet. Many organic use proxy server to stop direct access to outside resource .

If  you have application which have a logic to call external API. But due to proxy we can't call API directly. So, We need to enable proxy settings in our application to call external API.


We have two ways to configure proxy in .net application.

1. Setup proxy in web.config

2. Use "WebProxy" class for enable proxy

Setup proxy in web.config


You can use following code into web.config to use proxy.  Use proxyaddress to define proxy server path. here our proxy server address is "192.168.1.121:6588".


?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
<!--start proxy setting-->
  <system.net>
    <defaultProxy enabled="true"   useDefaultCredentials="true" >
      <proxy
        usesystemdefault="True"
        proxyaddress="http://192.168.1.121:6588"
        bypassonlocal="True"/>
      <bypasslist>
        <add address="[a-z]+\.bypasslist\.com" />
        <!--Provides a set of regular expressions that describe addresses that do not use the proxy. Localhost,Local IP address is best example of bypass list-->
      </bypasslist>
    </defaultProxy>
  </system.net>
  <!--end proxy setting-->
<!--start proxy setting-->
  <system.net>
    <defaultProxy enabled="true"   useDefaultCredentials="true" >
      <proxy
        usesystemdefault="True"
        proxyaddress="http://192.168.1.121:6588"
        bypassonlocal="True"/>
      <bypasslist>
        <add address="[a-z]+\.bypasslist\.com" />
        <!--Provides a set of regular expressions that describe addresses that do not use the proxy. Localhost,Local IP address is best example of bypass list-->
      </bypasslist>
    </defaultProxy>
  </system.net>
  <!--end proxy setting-->



defaultproxy settings

enabled    -    It specify that web proxy is enable or disable. The Default value is true.

useDefaultCredentials    -    It use for specify credentials for web proxy. The default value is false.

proxy settings

bypasslist - It use to specify addresses which not use proxy in regular expressions.

module - Use to specify new new proxy module to the application.

proxy - Use to  define a proxy server Settings

Like -usesystemdefault , proxyaddress, bypassonlocal

Use "WebProxy" class for enable proxy


Just add following keys into appSettings in web.config file. And enable/disable proxy to use inside code.

?
01
02
03
04
05
06
07
08
09
10
11
<appSettings>
     
    <add key="handleProxyInCode" value="true"/>
    <add key="proxyServerIPAddress" value="192.168.1.12"/>
    <add key="proxyServerPort" value="6588"/>
    <add key="proxyUseCustomNetworkCredential" value="true"/>
    <add key="proxyNetworkCredentialUserName" value="userName"/>
    <add key="proxyNetworkCredentialPassword" value="password"/>
    <add key="proxyNetworkCredentialDomain" value="domain"/>
   
</appSettings>
<appSettings>
    
    <add key="handleProxyInCode" value="true"/>
    <add key="proxyServerIPAddress" value="192.168.1.12"/>
    <add key="proxyServerPort" value="6588"/>
    <add key="proxyUseCustomNetworkCredential" value="true"/>
    <add key="proxyNetworkCredentialUserName" value="userName"/>
    <add key="proxyNetworkCredentialPassword" value="password"/>
    <add key="proxyNetworkCredentialDomain" value="domain"/>
  
</appSettings>

We are using WebProxy  class in "ProxyFromCode" API


?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;
namespace WebProxyTest.API
{
    [RoutePrefix("API/WebProxyTest")]
    public class WebProxyController : ApiController
    {
        /// <summary>
        /// Test proxy settings from web.config
        /// </summary>
        ///
        [Route("Test1")]
        [HttpGet]
        public IHttpActionResult ProxyFromConfig()
        {
            string url = @"http://jsonip.com";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "application/json";
            var response = request.GetResponse();
            StreamReader responsestream = new StreamReader(response.GetResponseStream());
            return Json( responsestream.ReadToEnd());
        }
        /// <summary>
        /// Test proxy settings to handle from code
        /// </summary>
        [Route("Test2")]
        [HttpGet]
        public IHttpActionResult ProxyFromCode()
        {
            string url = @"http://jsonip.com";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "application/json";
            //check that "handleProxyInCode" is true in web.config file
            bool enableProxyInCode = Convert.ToBoolean(ConfigurationManager.AppSettings["handleProxyInCode"]);
            //run this code when "handleProxyInCode" is true
            if (enableProxyInCode)
            {
                // Fetch proxy server settings from AppSettings section of Web.Config file
                string proxyServerAddress = ConfigurationManager.AppSettings["proxyServerIPAddress"];
                int proxyServerPort = Convert.ToInt16(ConfigurationManager.AppSettings["proxyServerPort"]);
                // Set proxy credentials from web.config file
                WebProxy proxy = new WebProxy(proxyServerAddress, proxyServerPort);
                proxy.Credentials = GetNetworkCredentialForProxy();
                request.Proxy = proxy;
            }
            var response = request.GetResponse();
            StreamReader responsestream = new StreamReader(response.GetResponseStream());
            return Json(responsestream.ReadToEnd());
        }
        /// <summary>
        /// Return network credential for proxy from web.config file
        /// </summary>
        /// <returns> <typeparamref name="ICredentials"/></returns>
        private ICredentials GetNetworkCredentialForProxy()
        {
            bool proxyUseCustomNetworkCredential = Convert.ToBoolean(ConfigurationManager.AppSettings["proxyUseCustomNetworkCredential"]);
            if (proxyUseCustomNetworkCredential)
            {
                string userName = ConfigurationManager.AppSettings["proxyNetworkCredentialUserName"];
                string password = ConfigurationManager.AppSettings["proxyNetworkCredentialPassword"];
                string domain = ConfigurationManager.AppSettings["proxyNetworkCredentialDomain"];
                return new NetworkCredential(userName, password, domain);
            }
            return System.Net.CredentialCache.DefaultCredentials;
        }
    }
  
}
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Http;

namespace WebProxyTest.API
{
    [RoutePrefix("API/WebProxyTest")]
    public class WebProxyController : ApiController
    {
        /// <summary>
        /// Test proxy settings from web.config
        /// </summary>
        /// 
        [Route("Test1")]
        [HttpGet]
        public IHttpActionResult ProxyFromConfig()
        {
            string url = @"http://jsonip.com";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "application/json";

            var response = request.GetResponse();
            StreamReader responsestream = new StreamReader(response.GetResponseStream());

            return Json( responsestream.ReadToEnd());
        }

        /// <summary>
        /// Test proxy settings to handle from code
        /// </summary>
        [Route("Test2")]
        [HttpGet]
        public IHttpActionResult ProxyFromCode()
        {

            string url = @"http://jsonip.com";

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.ContentType = "application/json";

            //check that "handleProxyInCode" is true in web.config file
            bool enableProxyInCode = Convert.ToBoolean(ConfigurationManager.AppSettings["handleProxyInCode"]);

            //run this code when "handleProxyInCode" is true
            if (enableProxyInCode)
            {
                // Fetch proxy server settings from AppSettings section of Web.Config file
                string proxyServerAddress = ConfigurationManager.AppSettings["proxyServerIPAddress"];
                int proxyServerPort = Convert.ToInt16(ConfigurationManager.AppSettings["proxyServerPort"]);

                // Set proxy credentials from web.config file
                WebProxy proxy = new WebProxy(proxyServerAddress, proxyServerPort);
                proxy.Credentials = GetNetworkCredentialForProxy();

                request.Proxy = proxy;
            }

            var response = request.GetResponse();
            StreamReader responsestream = new StreamReader(response.GetResponseStream());

            return Json(responsestream.ReadToEnd());
        }

        /// <summary>
        /// Return network credential for proxy from web.config file
        /// </summary>
        /// <returns> <typeparamref name="ICredentials"/></returns>
        private ICredentials GetNetworkCredentialForProxy()
        {
            bool proxyUseCustomNetworkCredential = Convert.ToBoolean(ConfigurationManager.AppSettings["proxyUseCustomNetworkCredential"]);

            if (proxyUseCustomNetworkCredential)
            {
                string userName = ConfigurationManager.AppSettings["proxyNetworkCredentialUserName"];
                string password = ConfigurationManager.AppSettings["proxyNetworkCredentialPassword"];
                string domain = ConfigurationManager.AppSettings["proxyNetworkCredentialDomain"];

                return new NetworkCredential(userName, password, domain);
            }
            return System.Net.CredentialCache.DefaultCredentials;
        }
    }

 
}
Previous
Next Post »
Thanks for your comment