我使用 Microsoft Graph API for C#.Net MVC 在 Outlook 日历中创建了一个事件,如下所示。
我相信任何将阅读此答案的人都已经在 https://apps.dev.microsoft.com 创建了一个应用程序并拥有在此使用的凭据。
请按照本教程How to use Outlook REST APIs 进行初始项目和 OAuth 设置。本文还讲述了如何创建如上所述的应用程序。
现在我做了以下编码。
创建将保存事件属性的类。
public class ToOutlookCalendar
{
public ToOutlookCalendar()
{
Attendees = new List<Attendee>();
}
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("body")]
public Body Body { get; set; }
[JsonProperty("start")]
public End Start { get; set; }
[JsonProperty("end")]
public End End { get; set; }
[JsonProperty("attendees")]
public List<Attendee> Attendees { get; set; }
[JsonProperty("location")]
public LocationName Location { get; set; }
}
public class Attendee
{
[JsonProperty("emailAddress")]
public EmailAddress EmailAddress { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public class EmailAddress
{
[JsonProperty("address")]
public string Address { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class Body
{
[JsonProperty("contentType")]
public string ContentType { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
}
public class LocationName
{
[JsonProperty("displayName")]
public string DisplayName { get; set; }
}
public class End
{
[JsonProperty("dateTime")]
public string DateTime { get; set; }
[JsonProperty("timeZone")]
public string TimeZone { get; set; }
}
在我的控制器(您将在上面提到的用于项目设置的 url 中使用的控制器)中,我创建了一个用于创建事件的操作方法,如下所示:
public async Task<ActionResult> CreateOutlookEvent()
{
string token = await GetAccessToken(); //this will be created in the project setup url above
if (string.IsNullOrEmpty(token))
{
// If there's no token in the session, redirect to Home
return Redirect("/");
}
using (HttpClient c = new HttpClient())
{
string url = "https://graph.microsoft.com/v1.0/me/events";
//with your properties from above except for "Token"
ToOutlookCalendar toOutlookCalendar = CreateObject();
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(toOutlookCalendar), Encoding.UTF8, "application/json");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = httpContent;
//Authentication token
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await c.SendAsync(request);
var responseString = await response.Content.ReadAsStringAsync();
}
return null;
}
用于创建虚拟事件对象的 CreateObject 方法(请原谅我的命名约定,但这仅用于演示目的)
public static ToOutlookCalendar CreateObject()
{
ToOutlookCalendar toOutlookCalendar = new ToOutlookCalendar
{
Subject = "Code test",
Body = new Body
{
ContentType = "HTML",
Content = "Testing outlook service"
},
Start = new End
{
DateTime = "2018-11-30T12:00:00",
TimeZone = "Pacific Standard Time"
},
End = new End
{
DateTime = "2018-11-30T15:00:00",
TimeZone = "Pacific Standard Time"
},
Location = new LocationName
{
DisplayName = "Harry's Bar"
}
};
return toOutlookCalendar;
}
我能够在 Outlook 日历中创建一个事件。此答案的某些部分改编自此THREAD。
希望对某人有所帮助。