Create A Typed HttpClient With HttpClientFactory In ASP.NET Core

HttpClient is used for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. But, HttpClient has some issues. To read more on the issues of HttpClient, you can check this link.
 
In the .NET Core 2.1 release, Microsoft has introduced a new way of designing HttpClients to solve these issues, and it's called HttpClientFactory. HttpClientFactory is an opinionated factory, available since .NET Core 2.1, for creating HttpClient instances in our applications. This means that we can create HttpClients and can register them in the HttpClientFactory in our application and can leverage the dependency injection capabilities of the .NET core to inject these HttpClients in our code. HttpClientFactory allows us to no longer care about the lifecycle of the HttpClient by leaving it to the framework.
 
There are three ways to use HttpClientFactory to instantiate HttpClients.
  • Default client
  • Named client
  • Typed client
In order to use the factory, we need to register it in the DI container. So, we need to use an extension method AddHttpClient() on IServiceCollection interface in our Startup.cs class. This will allow us to inject the HttpClient in our class constructors. 
 
In this article, we will see how to create a Typed HttpClient using the HttpClient factory in a .NET core MVC application and use it for making HTTP calls. I prefer Typed HttpClient over the other two because,
  1. As the name suggests, typed clients provide type safety.
  2. Typed clients help in encapsulating the API calls when we are making use of the HttpClient at one place, thus making our code DRY (Don't Repeat Yourself). The other two will scatter the implementation details of making HTTP calls throughout the codebase.

We will make a simple MVC application to learn the workings of typed HttpClient. This application will receive the name of a movie and call a REST API to fetch the details of that movie and shall display it to the user. I will be using Visual Studio Code for developing the application. The REST API used for fetching the movie details is the OMDB API. The OMDB API is a RESTful web service to obtain movie information. This is a free API with a 1000 requests per day limit for a user. We need an API key for accessing this API. To know more details about this API you can check their website.

Create a folder called MovieFinder and open it in VS Code. Create an MVC application by running the following command in the terminal. 

  1. dotnet new mvc --name MovieFinder  

This shall create a basic .NET Core MVC application. Now, let’s create a View Model class to hold the data from the OMDB API. So, let’s add a class named MovieDetailModel.

  1. public class MovieDetailModel  
  2. {  
  3.     public string Title { getset; }  
  4.     public string Year { getset; }  
  5.     public string Director { getset; }  
  6.     public string Actors { getset; }  
  7.     public string IMDBRating { getset; }  
  8.     public string PosterImage { getset; }  
  9.     public string Plot { getset; }  
  10. }  

 Now, we need to create an interface for our typed client. Let's name it IMovieDetailsClient.

  1. public interface IMovieDetailsClient  
  2. {  
  3.     Task<MovieDetailModel> GetMovieDetailsAsync(string movieName);  
  4. }  

This interface contains a single method, GetMovieDetailsAsync, which accepts the movie name as the parameter and shall return the details of that movie. Now we need to create a class which implements this interface. This class shall contain the actual logic of calling the OMDB API to fetch the movie details.

  1. public class MovieDetailsClient : IMovieDetailsClient  
  2. {  
  3.     private readonly HttpClient _httpClient;  
  4.   
  5.     public MovieDetailsClient(HttpClient httpClient)  
  6.     {  
  7.         httpClient.BaseAddress = new Uri("http://www.omdbapi.com/");  
  8.         _httpClient = httpClient;  
  9.     }  
  10.   
  11.     public async Task<MovieDetailModel> GetMovieDetailsAsync(string movieName)  
  12.     {  
  13.         var queryString = $"?t={movieName}&apikey=<your-api-key>";  
  14.         var response = await _httpClient.GetStringAsync(queryString);  
  15.   
  16.         JObject json = JObject.Parse(response);  
  17.   
  18.         if (json.SelectToken("Response").Value<string>() == "True")  
  19.         {  
  20.   
  21.             var movieDetails = new MovieDetailModel  
  22.             {  
  23.                 Title = json.SelectToken("Title").Value<string>(),  
  24.                 Year = json.SelectToken("Year").Value<string>(),  
  25.                 Director = json.SelectToken("Director").Value<string>(),  
  26.                 Actors = json.SelectToken("Actors").Value<string>(),  
  27.                 IMDBRating = json.SelectToken("imdbRating").Value<string>(),  
  28.                 PosterImage = json.SelectToken("Poster").Value<string>(),  
  29.                 Plot = json.SelectToken("Plot").Value<string>()  
  30.             };  
  31.   
  32.             return movieDetails;  
  33.         }  
  34.   
  35.         return new MovieDetailModel  
  36.         {  
  37.             Title = movieName  
  38.         };  
  39.     }  
  40. }  

In this class, we inject the HttpClient in our class constructor and set the base address of our OMDB API endpoint. We also implement GetMovieDetailsAsync method declared in our interface. We called the OMDB API from our method and mapped the API response to our view model and returned it. I have used the JSON.NET library for parsing the response from the API.

Note that I have hardcoded the API Base address and the API key in the code. This is not a healthy practice. We shall always prefer moving these kinds of values to configuration files and shall read those values from the configuration files in our code.
 
We have now created our typed client. Now let's create the view for user interaction. In the Index.cshtml file in the Views\Home folder, replace the existing code with the following code.
  1. @{  
  2.     ViewData["Title"] = "Home Page";  
  3. }  
  4.   
  5. @model MovieDetailModel  
  6.   
  7. <form   
  8.     asp-controller="Home"   
  9.     asp-action="Submit"  
  10.     method="post"   
  11.     class="form-horizontal"   
  12.     role="form">  
  13.   
  14.     <div class="form-group">  
  15.         <label for="Title">Title</label>  
  16.         <input   
  17.             class="form-control"   
  18.             placeholder="Enter Title"  
  19.             asp-for="Title">     
  20.     </div>  
  21.     <button type="submit" class="btn btn-primary">Submit</button>  
  22. </form>  
  23.   
  24.   
  25. @{  
  26.     <br>  
  27.       
  28.     if(!string.IsNullOrEmpty(Model?.Year))  
  29.     {  
  30.         var title = Model.Title;  
  31.         var year = Model.Year;    
  32.         var message = $"{title} is release on {year}";   
  33.    
  34.         <br>  
  35.         <div class="card" style="width: 18rem;">  
  36.             <img class="card-img-top" [email protected] alt="Poster Not Available">  
  37.             <div class="card-body">  
  38.                 <h5 class="card-title">@Model.Title (@Model.Year)</h5>  
  39.                 <p class="card-text">@Model.Plot</p>                
  40.             </div>  
  41.             <ul class="list-group list-group-flush">  
  42.                 <li class="list-group-item"><strong>Director : @Model.Director</strong></li>  
  43.                 <li class="list-group-item"><strong>Actors : @Model.Actors</strong></li>  
  44.                 <li class="list-group-item"><strong>Rating : @Model.IMDBRating</strong></li>  
  45.             </ul>  
  46.         </div>       
  47.     }  
  48.       
  49.     if(Model != null && string.IsNullOrEmpty(Model?.Year))  
  50.     {  
  51.         <div class="alert alert-danger" role="alert">  
  52.             <strong>Sorry!! Requested Movie Details are not available..</strong>   
  53.         </div>  
  54.     }  
  55. }  

Now, we need to add the Controller code for accepting the movie name from the view and for displaying the movie details. For that, we need to inject the typed client we had created into the constructor of our controller. So, we need to register this typed client with the HttpClient factory in our Startup.cs class. Add the following code in the ConfigureServices method in the startup class.

  1. services.AddHttpClient<IMovieDetailsClient, MovieDetailsClient>();  

Now, let's add our controller methods. In the HomeController make the changes as below.

  1. public class HomeController : Controller  
  2. {  
  3.     private readonly IMovieDetailsClient _movieDetailsClient;  
  4.   
  5.     public HomeController(IMovieDetailsClient movieDetailsClient)  
  6.     {  
  7.         _movieDetailsClient = movieDetailsClient;  
  8.     }  
  9.   
  10.     public IActionResult Index()  
  11.     {  
  12.         return View();  
  13.     }  
  14.   
  15.     [HttpPost]  
  16.     public async Task<IActionResult> Submit(MovieDetailModel model)  
  17.     {  
  18.         var movieDetail = await _movieDetailsClient.GetMovieDetailsAsync(model.Title);  
  19.         return View("Index", movieDetail);  
  20.     }        
  21. }  

We are injecting our IMovieDetails client in the constructor of our controller and assigning it to a read-only field _movieDetailsClient. We have also defined an action named Submit which takes the title of the movie from the view as a parameter. This method makes use of our typed HttpClient to fetch the details of that movie and shall return the view with the details of that movie.

Now, run the application. Execute the command dotnet run in the terminal. Open a browser and navigate to https://localhost:5001/. You shall see a page similar to this.

Create a Typed HttpClient with HttpClientFactory in ASP.NET Core
 
Enter a movie name in the text box and press the "Submit" button. You shall see a page similar to this.
 
Create a Typed HttpClient with HttpClientFactory in ASP.NET Core
 

Summary

 
In this article, we have looked at creating a typed HttpClient using the HttpClientFactory introduced in .NET Core 2.1 by developing an MVC application. You can read more about HttpClientFactory in the following links.