Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active May 20, 2021 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/8c64e364cd07f085050a89318b84ca4a to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/8c64e364cd07f085050a89318b84ca4a to your computer and use it in GitHub Desktop.
.NET Core Application - HttpClient, IHttpClientFactory and the middleware
// Code for Startup.cs
public class Startup
{
// Some other code...
public void ConfigureServices(IServiceCollection services)
{
// AddHttpClient middleware to register IHttpClientFactory dependencies
services.AddHttpClient();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Configure request pipeline
// Some middlewares
}
}
// Code for HomeController.cs
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IHttpClientFactory _clientFactory;
public HomeController(ILogger<HomeController> logger, IHttpClientFactory clientFactory)
{
_logger = logger;
_clientFactory = clientFactory;
}
public async Task<IActionResult> Index()
{
// Http Request
var request = new HttpRequestMessage(HttpMethod.Get,
"https://api.github.com/repos/dotnet/AspNetCore.Docs/branches");
// Http Headers
request.Headers.Add("Accept", "application/vnd.github.v3+json");
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
// Create HttpClient instance
var client = _clientFactory.CreateClient();
// HTTP API call
var response = await client.SendAsync(request);
// Handle Successful Response (or Error)
if (response.IsSuccessStatusCode)
{
using var responseStream = await response.Content.ReadAsStreamAsync();
dynamic branches = await JsonSerializer.DeserializeAsync
<IEnumerable<dynamic>>(responseStream);
}
else
{
// Error Handling
}
return View();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment