SlideShare a Scribd company logo
How to use proxy server in .net
application
Proxyserverisuse to distribute internetinsecure way. Proxyserveractsas an intermediaryfor
requestsfromclientsseekingresourcesfromotherserversorInternet.Manyorganicuse proxyserverto
stopdirectaccess to outside resource .
If youhave application whichhave alogicto call external API.Butdue toproxywe can't call APIdirectly.
So,We needtoenable proxysettingsinourapplicationtocall externalAPI.
We have twowaysto configure proxyin.netapplication.
1. Setupproxyin web.config
2. Use "WebProxy"classforenable proxy
1. Setupproxy in web.config
You can use followingcode intoweb.config touse proxy. Use proxyaddresstodefine proxyserverpath.
here our proxyserveraddressis"192.168.1.121:6588".
<!--startproxysetting-->
<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"/>
<!--Providesasetof regularexpressionsthatdescribe addressesthatdonotuse the proxy.
Localhost,Local IP addressisbestexample of bypasslist-->
</bypasslist>
</defaultProxy>
</system.net>
<!--endproxysetting-->
defaultproxysettings
Element Description
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.
Element Description
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
2. Use "WebProxy" classforenable proxy
Justadd followingkeysintoappSettingsinweb.configfile.Andenable/disableproxytouse inside code.
<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
Use of proxy in application
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Configuration;
usingSystem.IO;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Web;
usingSystem.Web.Http;
namespace WebProxyTest.API
{
[RoutePrefix("API/WebProxyTest")]
publicclassWebProxyController:ApiController
{
///<summary>
///Testproxysettingsfrom web.config
///</summary>
///
[Route("Test1")]
[HttpGet]
publicIHttpActionResultProxyFromConfig()
{
stringurl = @"http://jsonip.com";
HttpWebRequestrequest=WebRequest.Create(url) asHttpWebRequest;
request.ContentType ="application/json";
var response =request.GetResponse();
StreamReaderresponsestream=new StreamReader(response.GetResponseStream());
returnJson( responsestream.ReadToEnd());
}
///<summary>
///Testproxysettingstohandle fromcode
///</summary>
[Route("Test2")]
[HttpGet]
publicIHttpActionResultProxyFromCode()
{
stringurl = @"http://jsonip.com";
HttpWebRequestrequest=WebRequest.Create(url) asHttpWebRequest;
request.ContentType ="application/json";
//checkthat"handleProxyInCode"istrue inweb.configfile
bool enableProxyInCode =
Convert.ToBoolean(ConfigurationManager.AppSettings["handleProxyInCode"]);
//runthiscode when"handleProxyInCode"istrue
if (enableProxyInCode)
{
// FetchproxyserversettingsfromAppSettingssectionof Web.Configfile
stringproxyServerAddress=ConfigurationManager.AppSettings["proxyServerIPAddress"];
intproxyServerPort=Convert.ToInt16(ConfigurationManager.AppSettings["proxyServerPort"]);
// Setproxycredentialsfromweb.configfile
WebProxy proxy=new WebProxy(proxyServerAddress,proxyServerPort);
proxy.Credentials=GetNetworkCredentialForProxy();
request.Proxy=proxy;
}
var response =request.GetResponse();
StreamReaderresponsestream=new StreamReader(response.GetResponseStream());
returnJson(responsestream.ReadToEnd());
}
///<summary>
///Returnnetworkcredentialforproxyfromweb.configfile
///</summary>
///<returns><typeparamref name="ICredentials"/></returns>
private ICredentials GetNetworkCredentialForProxy()
{
bool proxyUseCustomNetworkCredential =
Convert.ToBoolean(ConfigurationManager.AppSettings["proxyUseCustomNetworkCredential"]);
if (proxyUseCustomNetworkCredential)
{
stringuserName =ConfigurationManager.AppSettings["proxyNetworkCredentialUserName"];
stringpassword= ConfigurationManager.AppSettings["proxyNetworkCredentialPassword"];
stringdomain= ConfigurationManager.AppSettings["proxyNetworkCredentialDomain"];
returnnew NetworkCredential(userName,password,domain);
}
returnSystem.Net.CredentialCache.DefaultCredentials;
}
}
}
Thanks
http://www.codeandyou.com
http://www.codeandyou.com/2015/09/How-to-use-
proxy-server-in-.net-application_16.html
Keywords - How to use proxy server in .net application, use proxy in .net
application, configuration of proxy in asp.net
Ad

Recommended

Php security
Php security
ssrajsathya
 
Captcha
Captcha
Salman Mushtaq
 
Workshop KrakYourNet2016 - Web applications hacking Ruby on Rails example
Workshop KrakYourNet2016 - Web applications hacking Ruby on Rails example
Anna Klepacka
 
Using jersey exception mapper
Using jersey exception mapper
Anirban Sen Chowdhary
 
Hacking Client Side Insecurities
Hacking Client Side Insecurities
amiable_indian
 
RoR Workshop - Web applications hacking - Ruby on Rails example
RoR Workshop - Web applications hacking - Ruby on Rails example
Railwaymen
 
Threat Hunting Web Shells Using Splunk
Threat Hunting Web Shells Using Splunk
jamesmbower
 
Demystifying REST
Demystifying REST
Kirsten Hunter
 
Rest API Security
Rest API Security
Stormpath
 
Step by step to install exchange server 2013 sp1
Step by step to install exchange server 2013 sp1
laonap166
 
How to CASifying PeopleSoft and Integrating CAS and ADFS
How to CASifying PeopleSoft and Integrating CAS and ADFS
John Gasper
 
Building an API Security Ecosystem
Building an API Security Ecosystem
Prabath Siriwardena
 
Introduction to Web security
Introduction to Web security
jeyaselvir
 
Apache course contents
Apache course contents
darshangosh
 
Data Import From the Server of The Central Bank of the Russian Federation: Ho...
Data Import From the Server of The Central Bank of the Russian Federation: Ho...
ADCI Solutions
 
Talking to Architects: Council for Aluminium in Building Mini Conference, Bra...
Talking to Architects: Council for Aluminium in Building Mini Conference, Bra...
Su Butcher
 
Nemchik
Nemchik
Kate Bilyk
 
Sites nao recomendados procon
Sites nao recomendados procon
Tatiana Faria
 
All about town city booklet
All about town city booklet
Shum Jun
 
iOs app localization / Yoni tsafir
iOs app localization / Yoni tsafir
geektimecoil
 
Persalinan normal
Persalinan normal
Septian Muna Barakati
 
How to setup ionic 2
How to setup ionic 2
codeandyou forums
 
Simulation of Formaldehyde Production Process
Simulation of Formaldehyde Production Process
Lê Thành Phương
 
David Crombie, HKU University of the arts utrecht @ICT 2015, TISP workshop
David Crombie, HKU University of the arts utrecht @ICT 2015, TISP workshop
TISP Project
 
Jillian michaels
Jillian michaels
student
 
Apricot juice business plan
Apricot juice business plan
Ejaz Dilshad
 
Taller Les bombolles del vi
Taller Les bombolles del vi
Laura Masramon
 
Personal Values Statement
Personal Values Statement
JoyeeLee0131
 
SLIDE FYDP2
SLIDE FYDP2
Noraishah Amin
 
Alexa, ask Skyscanner...
Alexa, ask Skyscanner...
David Low
 

More Related Content

What's hot (7)

Rest API Security
Rest API Security
Stormpath
 
Step by step to install exchange server 2013 sp1
Step by step to install exchange server 2013 sp1
laonap166
 
How to CASifying PeopleSoft and Integrating CAS and ADFS
How to CASifying PeopleSoft and Integrating CAS and ADFS
John Gasper
 
Building an API Security Ecosystem
Building an API Security Ecosystem
Prabath Siriwardena
 
Introduction to Web security
Introduction to Web security
jeyaselvir
 
Apache course contents
Apache course contents
darshangosh
 
Data Import From the Server of The Central Bank of the Russian Federation: Ho...
Data Import From the Server of The Central Bank of the Russian Federation: Ho...
ADCI Solutions
 
Rest API Security
Rest API Security
Stormpath
 
Step by step to install exchange server 2013 sp1
Step by step to install exchange server 2013 sp1
laonap166
 
How to CASifying PeopleSoft and Integrating CAS and ADFS
How to CASifying PeopleSoft and Integrating CAS and ADFS
John Gasper
 
Building an API Security Ecosystem
Building an API Security Ecosystem
Prabath Siriwardena
 
Introduction to Web security
Introduction to Web security
jeyaselvir
 
Apache course contents
Apache course contents
darshangosh
 
Data Import From the Server of The Central Bank of the Russian Federation: Ho...
Data Import From the Server of The Central Bank of the Russian Federation: Ho...
ADCI Solutions
 

Viewers also liked (18)

Talking to Architects: Council for Aluminium in Building Mini Conference, Bra...
Talking to Architects: Council for Aluminium in Building Mini Conference, Bra...
Su Butcher
 
Nemchik
Nemchik
Kate Bilyk
 
Sites nao recomendados procon
Sites nao recomendados procon
Tatiana Faria
 
All about town city booklet
All about town city booklet
Shum Jun
 
iOs app localization / Yoni tsafir
iOs app localization / Yoni tsafir
geektimecoil
 
Persalinan normal
Persalinan normal
Septian Muna Barakati
 
How to setup ionic 2
How to setup ionic 2
codeandyou forums
 
Simulation of Formaldehyde Production Process
Simulation of Formaldehyde Production Process
Lê Thành Phương
 
David Crombie, HKU University of the arts utrecht @ICT 2015, TISP workshop
David Crombie, HKU University of the arts utrecht @ICT 2015, TISP workshop
TISP Project
 
Jillian michaels
Jillian michaels
student
 
Apricot juice business plan
Apricot juice business plan
Ejaz Dilshad
 
Taller Les bombolles del vi
Taller Les bombolles del vi
Laura Masramon
 
Personal Values Statement
Personal Values Statement
JoyeeLee0131
 
SLIDE FYDP2
SLIDE FYDP2
Noraishah Amin
 
Alexa, ask Skyscanner...
Alexa, ask Skyscanner...
David Low
 
Lightning Talk #8: Digital Transformation in Asia – The Real Deal by Kanika A...
Lightning Talk #8: Digital Transformation in Asia – The Real Deal by Kanika A...
ux singapore
 
Creative Overview
Creative Overview
CreativeLogic Networking Private Limited
 
Skyscanner - Abandoning Conventional Wisdom
Skyscanner - Abandoning Conventional Wisdom
Janet Balneaves
 
Talking to Architects: Council for Aluminium in Building Mini Conference, Bra...
Talking to Architects: Council for Aluminium in Building Mini Conference, Bra...
Su Butcher
 
Sites nao recomendados procon
Sites nao recomendados procon
Tatiana Faria
 
All about town city booklet
All about town city booklet
Shum Jun
 
iOs app localization / Yoni tsafir
iOs app localization / Yoni tsafir
geektimecoil
 
Simulation of Formaldehyde Production Process
Simulation of Formaldehyde Production Process
Lê Thành Phương
 
David Crombie, HKU University of the arts utrecht @ICT 2015, TISP workshop
David Crombie, HKU University of the arts utrecht @ICT 2015, TISP workshop
TISP Project
 
Jillian michaels
Jillian michaels
student
 
Apricot juice business plan
Apricot juice business plan
Ejaz Dilshad
 
Taller Les bombolles del vi
Taller Les bombolles del vi
Laura Masramon
 
Personal Values Statement
Personal Values Statement
JoyeeLee0131
 
Alexa, ask Skyscanner...
Alexa, ask Skyscanner...
David Low
 
Lightning Talk #8: Digital Transformation in Asia – The Real Deal by Kanika A...
Lightning Talk #8: Digital Transformation in Asia – The Real Deal by Kanika A...
ux singapore
 
Skyscanner - Abandoning Conventional Wisdom
Skyscanner - Abandoning Conventional Wisdom
Janet Balneaves
 
Ad

Similar to How to use proxy server in .net application (7)

Proxy http ftp dns email
Proxy http ftp dns email
Heera K S
 
Uses of proxies
Uses of proxies
Proxies Rent
 
Proxy servers-firewalls
Proxy servers-firewalls
Ali Asgar Patanwala
 
Transparent proxy - SIP - 2014 - NCC LAB
Transparent proxy - SIP - 2014 - NCC LAB
Benith T
 
Proxy Servers
Proxy Servers
Sourav Roy
 
Web Proxy Server
Web Proxy Server
Mohit Dhankher
 
Proxy Servers
Proxy Servers
Sourav Roy
 
Proxy http ftp dns email
Proxy http ftp dns email
Heera K S
 
Transparent proxy - SIP - 2014 - NCC LAB
Transparent proxy - SIP - 2014 - NCC LAB
Benith T
 
Ad

More from codeandyou forums (16)

How to validate server certificate
How to validate server certificate
codeandyou forums
 
How to call $scope function from console
How to call $scope function from console
codeandyou forums
 
Understand components in Angular 2
Understand components in Angular 2
codeandyou forums
 
Understand routing in angular 2
Understand routing in angular 2
codeandyou forums
 
MongoDB 3.2.0 Released
MongoDB 3.2.0 Released
codeandyou forums
 
Welcome to ionic 2
Welcome to ionic 2
codeandyou forums
 
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
codeandyou forums
 
How to install ssl certificate from .pem
How to install ssl certificate from .pem
codeandyou forums
 
Protractor end-to-end testing framework for angular js
Protractor end-to-end testing framework for angular js
codeandyou forums
 
How routing works in angular js
How routing works in angular js
codeandyou forums
 
How to catch query string in angular js
How to catch query string in angular js
codeandyou forums
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular js
codeandyou forums
 
Angular.js interview questions
Angular.js interview questions
codeandyou forums
 
How to set up a proxy server on windows
How to set up a proxy server on windows
codeandyou forums
 
What is $root scope in angularjs
What is $root scope in angularjs
codeandyou forums
 
How to save log4net into database
How to save log4net into database
codeandyou forums
 
How to validate server certificate
How to validate server certificate
codeandyou forums
 
How to call $scope function from console
How to call $scope function from console
codeandyou forums
 
Understand components in Angular 2
Understand components in Angular 2
codeandyou forums
 
Understand routing in angular 2
Understand routing in angular 2
codeandyou forums
 
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
codeandyou forums
 
How to install ssl certificate from .pem
How to install ssl certificate from .pem
codeandyou forums
 
Protractor end-to-end testing framework for angular js
Protractor end-to-end testing framework for angular js
codeandyou forums
 
How routing works in angular js
How routing works in angular js
codeandyou forums
 
How to catch query string in angular js
How to catch query string in angular js
codeandyou forums
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular js
codeandyou forums
 
Angular.js interview questions
Angular.js interview questions
codeandyou forums
 
How to set up a proxy server on windows
How to set up a proxy server on windows
codeandyou forums
 
What is $root scope in angularjs
What is $root scope in angularjs
codeandyou forums
 
How to save log4net into database
How to save log4net into database
codeandyou forums
 

Recently uploaded (20)

Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
What is data visualization and how data visualization tool can help.pptx
What is data visualization and how data visualization tool can help.pptx
Varsha Nayak
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Migrating to Azure Cosmos DB the Right Way
Migrating to Azure Cosmos DB the Right Way
Alexander (Alex) Komyagin
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
Artificial Intelligence Workloads and Data Center Management
Artificial Intelligence Workloads and Data Center Management
SandeepKS52
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Meet You in the Middle: 1000x Performance for Parquet Queries on PB-Scale Dat...
Alluxio, Inc.
 
Zoneranker’s Digital marketing solutions
Zoneranker’s Digital marketing solutions
reenashriee
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
What is data visualization and how data visualization tool can help.pptx
What is data visualization and how data visualization tool can help.pptx
Varsha Nayak
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
Artificial Intelligence Workloads and Data Center Management
Artificial Intelligence Workloads and Data Center Management
SandeepKS52
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 

How to use proxy server in .net application

  • 1. How to use proxy server in .net application
  • 2. Proxyserverisuse to distribute internetinsecure way. Proxyserveractsas an intermediaryfor requestsfromclientsseekingresourcesfromotherserversorInternet.Manyorganicuse proxyserverto stopdirectaccess to outside resource . If youhave application whichhave alogicto call external API.Butdue toproxywe can't call APIdirectly. So,We needtoenable proxysettingsinourapplicationtocall externalAPI. We have twowaysto configure proxyin.netapplication. 1. Setupproxyin web.config 2. Use "WebProxy"classforenable proxy 1. Setupproxy in web.config You can use followingcode intoweb.config touse proxy. Use proxyaddresstodefine proxyserverpath. here our proxyserveraddressis"192.168.1.121:6588". <!--startproxysetting--> <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"/> <!--Providesasetof regularexpressionsthatdescribe addressesthatdonotuse the proxy. Localhost,Local IP addressisbestexample of bypasslist--> </bypasslist> </defaultProxy> </system.net> <!--endproxysetting--> defaultproxysettings Element Description 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.
  • 3. Element Description 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
  • 4. 2. Use "WebProxy" classforenable proxy Justadd followingkeysintoappSettingsinweb.configfile.Andenable/disableproxytouse inside code. <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 Use of proxy in application usingSystem; usingSystem.Collections.Generic; usingSystem.Configuration; usingSystem.IO; usingSystem.Linq; usingSystem.Net; usingSystem.Web; usingSystem.Web.Http; namespace WebProxyTest.API { [RoutePrefix("API/WebProxyTest")] publicclassWebProxyController:ApiController { ///<summary> ///Testproxysettingsfrom web.config ///</summary> /// [Route("Test1")] [HttpGet] publicIHttpActionResultProxyFromConfig() { stringurl = @"http://jsonip.com";
  • 5. HttpWebRequestrequest=WebRequest.Create(url) asHttpWebRequest; request.ContentType ="application/json"; var response =request.GetResponse(); StreamReaderresponsestream=new StreamReader(response.GetResponseStream()); returnJson( responsestream.ReadToEnd()); } ///<summary> ///Testproxysettingstohandle fromcode ///</summary> [Route("Test2")] [HttpGet] publicIHttpActionResultProxyFromCode() { stringurl = @"http://jsonip.com"; HttpWebRequestrequest=WebRequest.Create(url) asHttpWebRequest; request.ContentType ="application/json"; //checkthat"handleProxyInCode"istrue inweb.configfile bool enableProxyInCode = Convert.ToBoolean(ConfigurationManager.AppSettings["handleProxyInCode"]); //runthiscode when"handleProxyInCode"istrue if (enableProxyInCode) { // FetchproxyserversettingsfromAppSettingssectionof Web.Configfile stringproxyServerAddress=ConfigurationManager.AppSettings["proxyServerIPAddress"]; intproxyServerPort=Convert.ToInt16(ConfigurationManager.AppSettings["proxyServerPort"]); // Setproxycredentialsfromweb.configfile WebProxy proxy=new WebProxy(proxyServerAddress,proxyServerPort); proxy.Credentials=GetNetworkCredentialForProxy(); request.Proxy=proxy; } var response =request.GetResponse(); StreamReaderresponsestream=new StreamReader(response.GetResponseStream()); returnJson(responsestream.ReadToEnd()); } ///<summary> ///Returnnetworkcredentialforproxyfromweb.configfile
  • 6. ///</summary> ///<returns><typeparamref name="ICredentials"/></returns> private ICredentials GetNetworkCredentialForProxy() { bool proxyUseCustomNetworkCredential = Convert.ToBoolean(ConfigurationManager.AppSettings["proxyUseCustomNetworkCredential"]); if (proxyUseCustomNetworkCredential) { stringuserName =ConfigurationManager.AppSettings["proxyNetworkCredentialUserName"]; stringpassword= ConfigurationManager.AppSettings["proxyNetworkCredentialPassword"]; stringdomain= ConfigurationManager.AppSettings["proxyNetworkCredentialDomain"]; returnnew NetworkCredential(userName,password,domain); } returnSystem.Net.CredentialCache.DefaultCredentials; } } } Thanks http://www.codeandyou.com http://www.codeandyou.com/2015/09/How-to-use- proxy-server-in-.net-application_16.html Keywords - How to use proxy server in .net application, use proxy in .net application, configuration of proxy in asp.net