使用OneDrive REST API可恢复会话上传文件遇401未授权错误求助
OneDrive REST API 上传文件401未授权问题排查
我目前正尝试通过REST API将文件上传至OneDrive,但每次都会收到401未授权异常,错误提示为:
The remote server returned an error: (401) Unauthorized.
代码片段
public async Task<string> UploadFileAsync(Account account, StorageFile file) { var publicClientApplication = PublicClientApplicationBuilder.Create(MicrosoftConstants.ClientId) .WithRedirectUri(MicrosoftConstants.RedirectUri) .Build(); var scopes = new string[] { "files.readwrite.all" }; AuthenticationResult authToken = null; try { authToken = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync(); } catch (Exception) { } if (authToken != null) { var postData = new { item = new { name = file.Name } }; var json = JsonConvert.SerializeObject(postData); var request = (HttpWebRequest)WebRequest.Create($"https://graph.microsoft.com/v1.0/me/drive/items/root:/{file.Name}:/createUploadSession"); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength= json.Length; request.Headers["Authorization"] = "bearer" + authToken.AccessToken; using (var requestStream = await request.GetRequestStreamAsync()) using (var streamWriter = new StreamWriter(requestStream)) { streamWriter.Write(json); } var response = (HttpWebResponse)await request.GetResponseAsync(); } return string.Empty; }
错误排查与修复要点
- Authorization头格式错误:代码中
"bearer" + authToken.AccessToken缺少空格,正确格式应为"Bearer " + authToken.AccessToken(注意Bearer后必须加空格),这是导致401的核心原因之一。 - 异常被静默吞掉:
AcquireTokenInteractive的catch块为空,若获取token时出现权限不足、客户端ID/重定向URI配置错误等问题,无法得知具体原因,建议添加日志输出,比如catch (Exception ex) { Console.WriteLine($"获取Token失败:{ex.Message}"); }。 - 权限配置验证:确认Azure AD应用注册已添加
Files.ReadWrite.All权限,且已完成管理员同意(针对租户应用),否则获取的token不具备足够操作权限。 - ContentLength计算错误:
json.Length是字符串字符数,而HTTP请求的ContentLength需要是字节数(UTF-8编码下字符数和字节数可能不一致),正确做法是先将JSON转为字节数组再设置长度:var jsonBytes = Encoding.UTF8.GetBytes(json); request.ContentLength = jsonBytes.Length; await requestStream.WriteAsync(jsonBytes, 0, jsonBytes.Length); - 文件名URL编码:若文件名包含空格或特殊字符,直接拼接URL会导致请求无效,需对文件名进行URL编码,使用
Uri.EscapeDataString(file.Name)替换直接拼接的file.Name。
内容的提问来源于stack exchange,提问作者Valentin Maschenko
相关产品推荐
相关产品推荐

