.Net Core WebClient and proxy setup

How to Port Desktop Applications to .NET Core 3.0
In .net core, if you need to call 3rd party API, you may have to create an object of WebClient and do some steps to retrieve and send data to that API.
today I am going to explain to you  how you can create WebClient and how you can set up proxy settings in WebClient so you can call API throw proxy and retrieve any data. 

First of all, you need to create a dictionary of strings which can contain headers for 3rd party API, that code should be as following, you can add more parameters as per your need, for me, I just added one header.
public  Dictionary<stringstringGetHeaderForJson()
{
    Dictionary<stringstringheaders = new Dictionary<stringstring>();
    headers.Add("Content-Type""application/json");
    return headers;
}

 

one you created a header dictionary its time to create WebClient, I have made a method to get data from a post method,  inside it I have called another method to create WebClient and retrieve data after WebClient return data from API call.

 public async Task<RequestResponsePostJsonData(string baseAddressstring urlDictionary<stringstringheadersstring body,  IConfiguration _config=null)
{
    HttpClient client = GetHttpClient(_config);

    if (headers != null)
    {
        foreach (var header in headers)
        {
            client.DefaultRequestHeaders.TryAddWithoutValidation(header.Keyheader.Value);
        }
    }

    client.BaseAddress = new Uri(baseAddress);
    Encoding encoding = Encoding.UTF8;

    var result = await client.PostAsync(urlnew StringContent(bodyencoding"application/json")).ConfigureAwait(false);
    if (result.IsSuccessStatusCode)
    {
        return new RequestResponse { severity = "Success"httpResponse = result.Content.ReadAsStringAsync().ResultStatusCode = result.StatusCode };
    }
    else
    {
        return new RequestResponse { severity = "failure"httpResponse = result.Content.ReadAsStringAsync().ResultStatusCode = result.StatusCode };
    }
}





here the code for  GetHttpClient which actually creates WebClient object with or without proxy settings.

public HttpClient GetHttpClient(IConfiguration _config)
{
    bool ProxyEnable = Convert.ToBoolean(_config["GlobalSettings:ProxyEnable"]);

    HttpClient client = null;
    if (!ProxyEnable)
    {
        client = new HttpClient();
    }
    else
    {
        string ProxyURL = _config["GlobalSettings:ProxyURL"];
        string ProxyUserName = _config["GlobalSettings:ProxyUserName"];
        string ProxyPassword = _config["GlobalSettings:ProxyPassword"];
        string[] ExceptionURL = _config["GlobalSettings:ExceptionURL"].Split(';');
        bool BypassProxyOnLocal = Convert.ToBoolean(_config["GlobalSettings:BypassProxyOnLocal"]);
        bool UseDefaultCredentials = Convert.ToBoolean(_config["GlobalSettings:UseDefaultCredentials"]);

        WebProxy proxy = new WebProxy
        {
            Address = new Uri(ProxyURL),
            BypassProxyOnLocal = BypassProxyOnLocal,
            UseDefaultCredentials = UseDefaultCredentials,
            BypassList = ExceptionURL,
            Credentials = new NetworkCredential(ProxyUserNameProxyPassword)

        };

        HttpClientHandler handler = new HttpClientHandler { Proxy = proxy };
        client = new HttpClient(handler,true);
    }
    return client;
}


and appsettings look like this.

 {
    "GlobalSettings": {
    "ProxyEnable"true,
    "ProxyURL""http://proxy.gslb.shd.eradahcapital.com:3128",
    "ProxyUserName""",
    "ProxyPassword""",
    "BypassProxyOnLocal"true,
    "UseDefaultCredentials"true,
    "ExceptionURL""localhost;eradahcapital.com;10.*.*.*;192.*.*.*;172.20.*.*;172.30.*.*;172.31.*.*;172.22.*.*;172.23.*.*;172.24.*.*;172.25.*.*;eradahcapital.com;168.63.129.16;169.254.169.254"
  }
 }


you can enable disable proxy, also you can add more exception URL which will exempt from proxy and will access directly.


Comments

Popular posts from this blog

Setup source code of Visual studio on Bitbucket

Tables with ledger in sql server 2022