Created
May 3, 2020 21:41
-
-
Save manoj-choudhari-git/210ae3bfd1bf518d64ee23754097698b to your computer and use it in GitHub Desktop.
Home controller for web app calling web API scenario
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
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