Last active
May 22, 2021 19:31
-
-
Save manoj-choudhari-git/a08d9731f8516c63d76e4f8e0ba6e595 to your computer and use it in GitHub Desktop.
.NET Core Web Application - Startup.cs for registering typed client for making HTTP requests.
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 | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
// Use GitHubApiConsumer as key to the configurations | |
services.AddHttpClient<GitHubApionsumer>(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(); | |
} | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
// Request Pipeline... | |
} | |
} | |
// HomeController.cs | |
public class HomeController : Controller | |
{ | |
private readonly ILogger<HomeController> _logger; | |
private readonly GitHubApionsumer _gitHubApionsumer; | |
// Notice that GitHubApiConsumer is directly injected - IHttpClientFactory is not injected. | |
public HomeController(ILogger<HomeController> logger, GitHubApionsumer gitHubApionsumer) | |
{ | |
_logger = logger; | |
_gitHubApionsumer = gitHubApionsumer; | |
} | |
public async Task<IActionResult> Index() | |
{ | |
List<GitHubRepo> repoCollection = await _gitHubApionsumer.GetRepos(); | |
ViewBag.repoCollection = repoCollection; | |
return View(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment