Skip to content

Commit f3c7300

Browse files
committed
Catch exception precisely, and change an api url
1 parent ee18453 commit f3c7300

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

tests/DevApps/WebAppCallsMicrosoftGraph/Pages/Index.cshtml.cs

+19-12
Original file line numberDiff line numberDiff line change
@@ -29,30 +29,37 @@ public IndexModel(ILogger<IndexModel> logger, GraphServiceClient graphServiceCli
2929

3030
public async Task OnGet()
3131
{
32-
var user = await _graphServiceClient.Me.GetAsync(r =>
33-
r.Options.WithScopes("user.read")
34-
//.WithUser(User)
35-
);
36-
32+
try
33+
{
34+
var user = await _graphServiceClient.Me.GetAsync(r =>
35+
r.Options.WithScopes("user.read")
36+
//.WithUser(User)
37+
);
38+
ViewData["name"] = user.DisplayName;
39+
}
40+
catch (Exception)
41+
{
42+
ViewData["name"] = null;
43+
}
44+
3745
try
3846
{
3947
using (var photoStream = await _graphServiceClient.Me.Photo.Content.GetAsync())
4048
{
4149
byte[] photoByte = ((MemoryStream)photoStream).ToArray();
4250
ViewData["photo"] = Convert.ToBase64String(photoByte);
4351
}
44-
ViewData["name"] = user.DisplayName;
45-
46-
var graphData = await _downstreamApi.CallApiForUserAsync(
47-
"GraphBeta"
48-
);
49-
ViewData["json"] = await graphData.Content.ReadAsStringAsync();
5052
}
5153
catch (Exception)
5254
{
5355
ViewData["photo"] = null;
5456
}
5557

58+
var graphData = await _downstreamApi.CallApiForUserAsync(
59+
"GraphBeta"
60+
);
61+
ViewData["json"] = await graphData.Content.ReadAsStringAsync();
62+
5663
// Or - Call a downstream directly with the IDownstreamApi helper (uses the authorization header provider, encapsulates MSAL.NET)
5764
// See https://aka.ms/ms-id-web/downstream-web-api
5865
IDownstreamApi downstreamApi = HttpContext.RequestServices.GetService(typeof(IDownstreamApi)) as IDownstreamApi;
@@ -70,7 +77,7 @@ public async Task OnGet()
7077
new AuthorizationHeaderProviderOptions { BaseUrl = "https://graph.microsoft.com/v1.0/me"} );
7178
HttpClient client = new HttpClient();
7279
client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);
73-
HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/v1.0/users");
80+
HttpResponseMessage response = await client.GetAsync("https://graph.microsoft.com/v1.0/me");
7481

7582
// Or - Get a token if an SDK needs it (uses MSAL.NET)
7683
ITokenAcquirerFactory tokenAcquirerFactory = HttpContext.RequestServices.GetService(typeof(ITokenAcquirerFactory)) as ITokenAcquirerFactory;

0 commit comments

Comments
 (0)