Skip to content

Instantly share code, notes, and snippets.

@chinhvo
Forked from shubhamnikam/GithubController.cs
Created August 21, 2023 02:43
Show Gist options
  • Save chinhvo/19de468708e944a5558a2b26d056af4b to your computer and use it in GitHub Desktop.
Save chinhvo/19de468708e944a5558a2b26d056af4b to your computer and use it in GitHub Desktop.
Named Client implementation of IHttpClientFactory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace TestAPIGithub.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GithubController : ControllerBase
{
public readonly IHttpClientFactory _httpClientFactory;
public GithubController(IHttpClientFactory HttpClientFactory)
{
this._httpClientFactory = HttpClientFactory;
}
[HttpGet("GetProfile/{userName}")]
public async Task<IActionResult> GetProfile(string userName)
{
//create HttpClient instance using named factory
//GithubAPI - same as in ConfigureServices factory setup
var httpClient = _httpClientFactory.CreateClient("GithubAPI");
//http call
var profileInfo = await httpClient.GetStringAsync($"users/{userName}");
return Ok(profileInfo);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment