首页 > 解决方案 > 获取 findMeetingTimes POST WebRequest

问题描述

我正在尝试POST调用findMeetingTimes在 C# 中使用 Microsoft Graph

https://graph.microsoft.com/v1.0/users/{userid}/findMeetingTimes

要获取用户个人资料数据,我有以下内容:

IUserProfile IUserAuthentication.GetProfileData(string accessToken)
{
    MicrosoftUserProfile profile = new MicrosoftUserProfile();
    try
    {
        string url = "https://graph.microsoft.com/v1.0/me";
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers.Add("Authorization", "Bearer " + accessToken);
        WebRequests webReq = new WebRequests();
        string response = webReq.GetRequest(url, headers);
        profile = JsonConvert.DeserializeObject<MicrosoftUserProfile>(response);
    }
    catch (Exception)
    {
        throw;
    }
    return profile;
}

public string GetRequest(string url, IDictionary<string, string> headers)
{
    string returned = "";
    try
    {
        System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url);
        webRequest.Method = "GET";
        if (headers.Count > 0)
        {
            foreach (var item in headers)
            {
                webRequest.Headers.Add(item.Key, item.Value);
            }
        }
        System.Net.WebResponse resp = webRequest.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
        returned = sr.ReadToEnd().Trim();
    }
    catch (Exception)
    {
        throw;
    }
    return returned;
}

标签: c#microsoft-graph-api

解决方案


对您的最佳建议是直接使用Microsoft Graph 客户端库,而不是使用 HttpClient。安装库后,只需使用以下代码:

graphClient.Me.FindMeetingTimes().Request().PostAsync()

这是使您的代码更具可读性的一种简单而有效的方法。

当然,你也可以通过模仿以下代码来编写自己的逻辑:

 // 1. Create request message with the URL for the trending API.
string requestUrl = "https://graph.microsoft.com/V1.0/me/findMeetingTimes";
HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);

// 2. Authenticate (add access token) our HttpRequestMessage
graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm).GetAwaiter().GetResult();

// 3. Send the request and get the response.
HttpResponseMessage response = graphClient.HttpProvider.PostAsync(hrm).Result;

// 4. Get the response.
var content = response.Content.ReadAsStringAsync().Result;
JObject responseBody = JObject.Parse(content);

// 4. Get the array of objects from the 'value' key.
JToken arrayOfObjects = responseBody.GetValue("value");

推荐阅读