在使用 Microsoft Graph API 查询 Shifts 时出现错误 "应用程序上下文请求需要设置 MS-APP-ACTS-AS 头部" 通常是因为你的请求未正确设置应用程序上下文。
下面是一个示例的解决方法,代码使用 C# 编写:
using Microsoft.Graph;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
// 创建一个 HttpClient 对象
using (var httpClient = new HttpClient())
{
// 设置请求的头部信息
httpClient.DefaultRequestHeaders.Add("MS-APP-ACTS-AS", "user@contoso.com");
// 创建一个 GraphServiceClient 对象
var graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(async (requestMessage) =>
{
// 设置 HttpClient 对象到 GraphServiceClient
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken());
// 将 HttpClient 对象传递给 GraphServiceClient
requestMessage.SetHttpClient(httpClient);
}));
// 使用 GraphServiceClient 查询 Shifts
var shifts = await graphClient.Teams["{team-id}"].Schedule.Shifts.Request().GetAsync();
}
}
static async Task<string> GetAccessToken()
{
// TODO: 获取访问令牌的逻辑
return "<access-token>";
}
}
上述代码示例中,我们使用 HttpClient 对象设置了 "MS-APP-ACTS-AS" 头部,该头部指定了应用程序上下文请求的用户。
然后,我们使用 GraphServiceClient 对象进行 Shifts 的查询。请注意,我们通过将 HttpClient 对象传递给 GraphServiceClient 对象来确保请求包含正确的头部信息。
请替换示例代码中的占位符 {team-id}
和 "<access-token>"
为你的实际值。同时,你需要实现 GetAccessToken
方法来获取访问令牌。
希望这个示例能够帮助你解决问题。