我现在已经设法解决了这个问题。该解决方案有点破解,但它有效。我原来的调用代码如下:
public static async Task AddEvent(Event e)
{
using (var client = new HttpClient())
{
using (var req = new HttpRequestMessage(HttpMethod.Post, _calendarUrl))
{
var token = await GetToken();
req.Headers.Add("Authorization", string.Format("Bearer {0}", token));
req.Headers.TryAddWithoutValidation("Content-Type", "application/json");
var requestContent = JsonConvert.SerializeObject(new
{
Subject = e.Subject,
Body = new
{
ContentType = "HTML",
Content = e.Body.Content
},
Start = new
{
DateTime = e.Start,
TimeZone = "UTC"
},
End = new
{
DateTime = e.End,
TimeZone = "UTC"
}
});
req.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
using (var response = await client.SendAsync(req))
{
if (response.IsSuccessStatusCode)
{
return;
}
else
{
throw new HttpRequestException("Event could not be added to calendar");
}
}
}
}
}
我现在已将其更改为:
public static async Task AddEvent(Event e)
{
using (var client = new HttpClient())
{
using (var req = new HttpRequestMessage(HttpMethod.Post, _calendarUrl))
{
var token = await GetToken();
req.Headers.Add("Authorization", string.Format("Bearer {0}", token));
req.Headers.TryAddWithoutValidation("Content-Type", "application/json");
IList<Attendee> attendees = new List<Attendee>();
foreach(var a in e.Attendees)
{
attendees.Add(new Attendee()
{
EmailAddress = a.EmailAddress,
Type = Enum.GetName(typeof(AttendeeType), AttendeeType.Optional)
});
}
var requestContent = JsonConvert.SerializeObject(new
{
Subject = e.Subject,
Body = new
{
ContentType = "HTML",
Content = e.Body.Content
},
Start = new
{
DateTime = e.Start,
TimeZone = "UTC"
},
End = new
{
DateTime = e.End,
TimeZone = "UTC"
},
Attendees = attendees
});
req.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
using (var response = await client.SendAsync(req))
{
if (response.IsSuccessStatusCode)
{
return;
}
else
{
throw new HttpRequestException("Event could not be added to calendar");
}
}
}
}
}
以及添加以下本地类:
private class Attendee
{
public EmailAddress EmailAddress { get; set; }
public string Type { get; set; }
}
本质上,图表参与者期望:
1. 包含名称(字符串)和电子邮件(字符串)的 EmailAddress 对象。
2. AttendeeType 类型的 Type 对象,它是未正确传递的枚举。
因此,我创建了自己的 Attendee 类版本,以包含与 API 期望的相同的 EmailAddress 对象和类型字符串的类型。
然后我不得不将枚举类型更改为枚举的名称而不是 int 值。这样做如下:
attendees.Add(new Attendee()
{
EmailAddress = a.EmailAddress,
Type = Enum.GetName(typeof(AttendeeType), AttendeeType.Optional)
});
这给了我值“可选”而不是 1,这使得它可以被 API 接受。
我希望这对将来的某人有所帮助。
在代码中使用枚举并期望在 API 中使用字符串而不是整数,这似乎是微软的主要疏忽,我认为这需要解决。