使用Office 365 API创建新事件

时间:2016-11-11 15:44:20

标签: asp.net office365api

我得到Error 401 Not Authorized

我已经配置了所有内容,下面的代码正在通过Button运行:

//Karim
string postData = "{\"Subject\": \"Discuss the Calendar REST API\",\"Body\": {\"ContentType\": \"HTML\",\"Content\": \"I think it will meet our requirements!\"},\"Start\": {\"DateTime\": \"2016 - 02 - 02T18: 00:00\",\"TimeZone\": \"Pacific Standard Time\"},\"End\": {\"DateTime\": \"2016 - 02 - 02T19: 00:00\",\"TimeZone\": \"Pacific Standard Time\"}}";
string Url = "https://outlook.office.com/api/v2.0/me/events";
HttpWebRequest myHttpWebRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
myHttpWebRequest.Method = "POST";

byte[] data = Encoding.ASCII.GetBytes(postData);

myHttpWebRequest.ContentType = "application/json";
myHttpWebRequest.Accept = "application/json";
myHttpWebRequest.ContentLength = data.Length;

Stream requestStream = myHttpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

Stream responseStream = myHttpWebResponse.GetResponseStream();

StreamReader myStreamReader = new StreamReader(responseStream, Encoding.Default);

this.Label1.Text = myStreamReader.ReadToEnd();

myStreamReader.Close();
responseStream.Close();

myHttpWebResponse.Close();
//End Karim

我已经配置了Office 365开发人员工具,NuGet,我正在使用Visual Studio 2015。

1 个答案:

答案 0 :(得分:0)

必须对请求进行身份验证和授权才能请求这些API。确实谁会成为" / me"如果您没有提供代表您提出此类请求的任何信息?

要做到这一点,你应该设置一个所谓的身份验证承载,在你的C#.NET调用中看起来像这样

request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "<your access token as string here>");

要了解如何检索此类访问令牌,请从this documentation开始。