Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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