Last active
May 21, 2021 19:18
-
-
Save manoj-choudhari-git/a00bd8b10bd86c0084581333919ebb1c to your computer and use it in GitHub Desktop.
.NET Core Application - IHttpClientFactory and Add Http Client middleeware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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