Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active May 21, 2021 19:18
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/a00bd8b10bd86c0084581333919ebb1c to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/a00bd8b10bd86c0084581333919ebb1c to your computer and use it in GitHub Desktop.
.NET Core Application - IHttpClientFactory and Add Http Client middleeware
// Startup.cs
public class Startup
{
// Some code...
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("github", c =>
{
c.BaseAddress = new Uri("https://api.github.com/");
// Github API versioning
c.DefaultRequestHeaders.Add("Accept", "application/vnd.github.v3+json");
// Github requires a user-agent
c.DefaultRequestHeaders.Add("User-Agent", "theCodeBlogger.com Demo");
});
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Request process pipeline...
}
}
// 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()
{
// URL not specifying base address and no request headers
var request = new HttpRequestMessage(HttpMethod.Get,
"/repos/dotnet/AspNetCore.Docs/branches");
// Create HttpClient by providing name
// Use same name which is used while configuring CreateClient
var client = _clientFactory.CreateClient("github");
var response = await client.SendAsync(request);
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