日历事件插入失败 "Login Required" C#/REST



我创建了一个web应用程序,旨在让人们有机会与我预约,我使用业务逻辑来验证时间是否有效。我把所有的约会都放在谷歌日历上。所以我去了谷歌API控制台创建的Web应用程序项目。我得到了我的客户id和秘密。我可以很好地检索访问令牌。我甚至有刷新令牌和构建的逻辑来自动刷新访问令牌,这很好。我使用这个令牌来检索日历事件的列表,这很好。然后,我使用令牌插入一个新的日历事件,结果出现错误。首先是代码:

public CalendarEvent InsertCalendarEvent(CalendarEditArgs args)
{
string url = "https://www.googleapis.com/calendar/v3/calendars/" + HttpUtility.UrlEncode(args.CalendarId) + "/events?&key=" + args.APIKey;
Web.SetUpPost(url, null, true, JsonConvert.SerializeObject(args.Event), null, null, new { Name = "Authorization", Value = "Bearer " + args.AccessToken }, new { Name = "X-JavaScript-User-Agent", Value = "Easy SPS" });
string response = null;
try
{
response = Web.GetResponse(); 
return JsonConvert.DeserializeObject<CalendarEvent>(response);
}
catch(WebException e)
{
response = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();
throw new Exception(response, e);
}

}
public void SetUpPost(string url, string parameters, bool json, string body, string clientKey, string clientSecret, params object[] data)
{
if (body != null && parameters != null)
throw new InvalidOperationException("You cannot submit a request body and parameters at the same time.");
request =  WebRequest.Create(url) as HttpWebRequest;

if (!json)
{
request.ContentType = "application/x-www-form-urlencoded";
}
else
{
request.ContentType = "application/json";
}
request.Headers.Add("Accept-Charset", "utf-8");
request.Method = "POST";
request.Referer = "https://www.easy-sps.com";
request.KeepAlive = true;
byte[] bytes = null;
if (body != null || parameters != null)
{
bytes = System.Text.Encoding.ASCII.GetBytes(body == null ? parameters : body);
request.ContentLength = bytes.Length;
System.IO.Stream os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Push it out there
os.Close();
}
else
{
request.ContentLength = 0;
}
if (data != null)
{
foreach (var dataObject in data)
{
PropertyInfo prop = dataObject.GetType().GetProperties()[0];
PropertyInfo prop2 = dataObject.GetType().GetProperties()[1];
request.Headers.Add(prop.GetValue(dataObject, null).ToString(), prop2.GetValue(dataObject, null).ToString());
}
}
}
}
The error I get:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}

注意,我实际上并没有使用clientkey和client secret,因为它们是用来获取令牌的,而不是使用它。要检索令牌,我必须以离线访问的方式登录谷歌(我知道这很有效,因为谷歌表示即使我不在线,我也会授予访问日历的权限)。我去了谷歌游乐场,在那里我可以让它工作,但在这里不行。我试图找出我发布的内容和它发布的内容之间的区别,但我什么都找不到。如有任何帮助,我们将不胜感激。一个多星期以来,我一直处于零进度状态,正如我们所知,谷歌并不直接支持它的开发者,只是通过它的论坛,我在那些论坛上找不到我还没有尝试过的东西。

Google提供了一个围绕日历api的.Net包装器。请参阅《.NET客户端库开发人员指南》。

我通过在url"access_token="中放入访问令牌来解决问题。为什么它在URL中有效,但在标题中无效,我无法理解。

最新更新