Tutorial: Call an API and display the results

The application can now be configured to call an API. For the purposes of this tutorial, the Microsoft Graph API will be called to display the profile information of the logged-in user.

In this tutorial:

  • Call the API and display the results
  • Test the application


Call the API and display the results

  1. Under Pages, open the Index.cshtml.cs file and replace the entire contents of the file with the following snippet. Check that the project namespace matches your project name.

    using System.Net;
    using System.Text.Json;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.Identity.Web;
    namespace sign_in_webapp.Pages;
    [AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
    public class IndexModel : PageModel
        private readonly ILogger<IndexModel> _logger;
        private readonly IDownstreamWebApi _downstreamWebApi;
        public IndexModel(ILogger<IndexModel> logger,
                            IDownstreamWebApi downstreamWebApi)
            _logger = logger;
            _downstreamWebApi = downstreamWebApi;
        public async Task OnGet()
            using var response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi").ConfigureAwait(false);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                var apiResult = await response.Content.ReadFromJsonAsync<JsonDocument>().ConfigureAwait(false);
                ViewData["ApiResult"] = JsonSerializer.Serialize(apiResult, new JsonSerializerOptions { WriteIndented = true });
                var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                throw new HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
  2. Open Index.cshtml and add the following code to the bottom of the file. This will handle how the information received from the API is displayed:

    <p>Before rendering the page, the Page Model was able to make a call to Microsoft Graph's <code>/me</code> API for your user and received the following:</p>
    <p><pre><code class="language-js">@ViewData["ApiResult"]</code></pre></p>
    <p>Refreshing this page will continue to use the cached access token acquired for Microsoft Graph, which is valid for future page views will attempt to refresh this token as it nears its expiration.</p>

Test the application

  1. Start the application by selecting Start without debugging.
  1. Depending on your IDE, you may need to enter the application URI into the browser, for example https://localhost:7100. After the sign in window appears, select the account in which to sign in with. Ensure the account matches the criteria of the app registration.

    Screenshot depicting account options to sign in.

  2. Upon selecting the account, a second window appears indicating that a code will be sent to your email address. Select Send code, and check your email inbox.

    Screenshot depicting a screen to send a code to the user's email.

  3. Open the email from the sender Microsoft account team, and enter the 7-digit single-use code. Once entered, select Sign in.

    Screenshot depicting the single-use code sign in procedure.

  4. For Stay signed in, you can select either No or Yes.

    Screenshot depicting the option on whether to stay signed in.

  5. The app will ask for permission to sign in and access data. Select Accept to continue.

    Screenshot depicting the permission requests.

  6. The web app now displays profile data acquired from the Microsoft Graph API.

    Screenshot depicting the results of the API call.

Next steps

Learn how to use the Microsoft identity platform by trying out the following tutorial series on how to build a web API.