Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created May 3, 2020 21:41
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/210ae3bfd1bf518d64ee23754097698b to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/210ae3bfd1bf518d64ee23754097698b to your computer and use it in GitHub Desktop.
Home controller for web app calling web API scenario
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ITokenAcquisition _tokenAcquisition;
public HomeController(ILogger<HomeController> logger, ITokenAcquisition tokenAcquisition)
{
_logger = logger;
_tokenAcquisition = tokenAcquisition;
}
public async Task<IActionResult> Index()
{
//// Acquire the access token.
string[] scopes = new string[] { "api://5e971e5c-a661-4d82-ba97-935480492129/access_as_user" };
string accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(scopes);
// Use the access token to call a protected web API.
HttpClient client = new HttpClient();
string url = "https://localhost:44389/weatherforecast";
// Set Bearer Token
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
// Call API
string json = await client.GetStringAsync(url);
var apiOutput = JsonConvert.DeserializeObject<List<WeatherForecast>>(json);
// Send Data To View
return View(apiOutput);
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment