usingvar response = await _downstreamWebApi.CallWebApiForUserAsync("DownstreamApi", op => op.RelativePath = "/me/messages?$select=subject").ConfigureAwait(false);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var apiResult = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// Do somethingreturn apiResult;
}
else
{
var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
thrownew HttpRequestException($"Invalid status code in the HttpResponseMessage: {response.StatusCode}: {error}");
}
使用 GraphServiceClient
var result = await _client.Me.Messages.Request().Select(x => x.Subject).GetAsync().ConfigureAwait(false);
return result.Select(x => x.Subject).ToArray();
在桌面客户端中调用Web API
注册应用程序(最好是单独注册一个)
使用 Microsoft.Identity.Client 登录并获取凭据
using Microsoft.Identity.Client;
var scopes = new[] { "api://d4755e4f-9ff6-463a-afed-ebd9c40d73d7/access_as_user", "mail.read", "user.read" };
var tenantId = "3a6831ab-6304-4c72-8d08-3afe544555dd";
var clientId = "1c6b9008-113d-4854-afd3-e3f5bd726ce7";
var pca = PublicClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithRedirectUri("http://localhost")
.Build();
var result = await pca.AcquireTokenInteractive(scopes)
.ExecuteAsync();
使用凭据访问Webapi
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
var temp = await client.GetAsync("https://localhost:7032/test");
Console.WriteLine(await temp.Content.ReadAsStringAsync());