.NET Core 2.1 – Use HttpClientFactory to implement resilient HTTP requests

The original and well-know HttpClient class can be easily used, but in some cases, it is not being properly used by many developers.

As a first issue, while this class is disposable, using it with the using statement is not the best choice because even when you dispose HttpClient object, the underlying socket is not immediately released and can cause a serious issue named ‘sockets exhaustion’.

Therefore, HttpClient is intended to be instantiated once and reused throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. That issue will result in SocketException errors. Possible approaches to solve that problem are based on the creation of the HttpClient object as singleton or static.

But there’s a second issue with HttpClient that you can have when you use it as singleton or static object. In this case, a singleton or static HttpClient doesn’t respect DNS changes.

To address those mentioned issues and make the management of HttpClient instances easier, .NET Core 2.1 offers a new HttpClientFactory that can also be used to implement resilient HTTP calls by integrating Polly with it.

Read more…

I hope this will help !!!!

 

AWS API Gateway – API Creation with Lambda Proxy Integration and Web Page Redirection (302) using .NET Core 2.0

In this article, we will see how to create and test an API with Lambda proxy integration using the API Gateway console. We will also see how a Lambda backend parses the query string request and implements app logic that depends on the incoming query string parameters. we will also see how to create 302 Redirect response using Lambda function and redirect caller directly to web page.

Topic to cover in this article

  1. How to create Lambda function for Lambda Proxy Integration using .NET core 2.0?
  2. How to create Resource?
  3. How to create HTTP GET Method with Lambda Proxy Integration?
  4. How to setup Request query string parameter?
  5. How to setup Response redirect (HttpStatus=302) with Location header parameter?

Step-1: Create Lambda function for Lambda Proxy Integration using .NET core 2.0

Create New AWS Lambda Project “ApiLambdaVerifyEmail” using Visual Studio 2017 version 15.5.6:

01-Create-LambdaFunction-DotNetCore

Add following NuGet Packages for Lambda function which will be needed for API Gateway Proxy Request and Response and other Lambda features:

02-NuGet-Packages-Used.JPG

Update Function Handler Code with below code snippets:


public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest input, ILambdaContext context)
{
    //Ready query string parameter
    string queryString ;
    input.QueryStringParameters.TryGetValue("pageKey", out queryString);

    //Set Default URL if no match found
    string redirectUrl = @"https://ramanisandeep.wordpress.com/";

    if(!string.IsNullOrEmpty(queryString))
    {
        Console.WriteLine("pageKey : " + queryString);
    }

    //Use Query String Parameters to do some DB Operation 

    //Based on database operation redirect page to X Web Page or Y Web Page or Z Web Page
    switch (queryString)
    {
        case "google":
            redirectUrl = @"https://www.google.co.in";
            break;
        case "twitter":
            redirectUrl = @"https://twitter.com";
            break;
        case "sandeep":
            redirectUrl = @"https://ramanisandeep.wordpress.com/";
            break;
    }

    Console.WriteLine("URL : " + redirectUrl);

    //Redirect to Web Page using 302 Response Code and URL
    var response = new APIGatewayProxyResponse
    {
        StatusCode = (int)HttpStatusCode.Redirect,
        Headers = new Dictionary { { "location", redirectUrl } }
    };

    return response;
}

 

What above code does is:

  • Read query string parameters – pageKey
  • Based on query string parameter values – set redirect URLfor the response.
  • Create APIGatewayProxyResponse object with page redirection (302) Status code and add header location for the page where to redirect.

Publish Lambda function by right clicking Project on solution explorer

03-PublishToLambda-Step-1

Next, It will display Upload Lambda function popup where you can select/define your profile, region and Lambda function name and press Next button:

04-Upload-Lambda-function

Next, It will display popup to select permissions for Lambda function you are uploading and once you select Role then press Upload button:

05-Upload-Lambda-function-2

Note: Create Role for Lambda function if you haven’t created yet using IAM console as per your Lambda function Access Requirements. For this article we are not accessing any other AWS Service from Lambda function so no role as such required.

Next step is to create API Gateway API with Lambda Proxy Integration.

Step-2: Create Resource – TestRedirectPage :

How to setup Resource guide from AWS?

1-New-Resource-Creation.JPG

Step-3: Setup GET Method with Lambda Proxy Integration: 

How to setup HTTP Method guide from AWS?

2-Setup-Get-Method-For-Lambda-Proxy-Integration

3-Add permission to lambda function-confirmation

After GET Method configuration is saved it will show all request / response configuration on screen:

4-Method-Execution.JPG

Step-4: Setup Query String Parameters for API Gateway – pageKey:

5-Add-QueryString-Method-Request.JPG

Verify GET Integration Request Type is LAMBDA_PROXY:

6-Get-IntegrationRequesst.JPG

Step-5: Setup GET Method Response redirect (HttpStatus=302) with Location header parameter:

When setting up the API Gateway Method Response, start by declaring the status code in the Method Response section. 200 will already be there so delete it. Add your 302 here instead and add the Location response header.

7-Get-Method-Response.JPG

After above all configurations are done, Method Execution will look like:

8-Method-Execution-AfterConfigurations.JPG

Test GET Method we configured by clicking Test link.

  • Set Query Strings textbox “pageKey=sandeep” and press test button.

9-Get-Method-Test.JPG

Deploy API

  • Select GET method
  • then click on Actions button on top
  • then select deploy api option
  • select/create Dev stage and press Deploy button

10-Deploy-Api-Dev.JPG

Get Invoke URL from Dev environment

  • select GET method of testredirectpage resource
  • then it will display invoke URL
  • by using this URL we can hit API gateway resource and execute method from browser or Postman.

11-InvokeUrl-Dev-Stage.JPG

Run this Invoke URL in Browsser by Adding Query String pageKey=sandeep

12-Test-ApiUrl-With-querystring-2-input

Browser will invoke GET API method of testredirectpage resource on API gateway and then run our lambda function endpoint, then lambda function will parse this query string value, then send response to redirect Url=https://ramanisandeep.wordpress.com , then browser will redirect https://ramanisandeep.wordpress.com page.

13-Test-Output-result-sandeep.JPG

Similarly, you can test with other Query String parameters and see which web page opens 🙂

I hope this is useful.