通过MS Graph API上传Drive文件遇资源未找到问题求助
问题描述
尝试通过MS Graph API上传小于4MB的.xlsx文件到指定Drive位置,执行代码时出现错误:Resource not found for the segment Oks
原代码
public static string DecodeData(string encodedData) { byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData); string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes); return returnValue; } // Upload files to SharePoint public void SharePointUploadDriveItems(string accessToken) { var httpClient = new HttpClient(); try { string path = @"C:\\StockLevelReportLocation\\New Files\\TestFileUpload.xlsx"; byte[] filebytes = System.IO.File.ReadAllBytes(path); using (var client = new HttpClient()) { string fileName = "TestFileToUpload.txt"; using (var request = new HttpRequestMessage(HttpMethod.Put, "https://graph.microsoft.com/v1.0/drives/root/Oks/Stock Report/TestFileUpload.xlsx/content")) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); request.Headers.Add("Accept", "application/json;odata.metadata=verbose"); request.Content = new StringContent(DecodeData(Convert.ToBase64String(filebytes)), System.Text.Encoding.ASCII, "text/plain"); var driveItemsResponse = httpClient.SendAsync(request).Result; var driveItemsResponseContent = driveItemsResponse.Content.ReadAsStringAsync().Result; } } } catch (Exception ex) { throw new Exception(ex.ToString()); } }
错误原因及修复方案
1. API路径格式错误
Graph API访问Drive文件的标准语法要求drives/root后使用:/路径:/content的格式,原URL缺少路径前后的:/,导致API无法正确识别Oks这个路径段,触发资源找不到的错误。
正确的请求URL应为:https://graph.microsoft.com/v1.0/drives/root:/Oks/Stock Report/TestFileUpload.xlsx:/content
2. 文件内容处理逻辑错误
DecodeData方法完全多余,且用ASCII编码处理二进制文件(xlsx属于二进制格式)会丢失字节,破坏文件结构。直接使用文件字节数组作为请求内容即可,无需Base64转码再解码。- 请求内容的MediaType设置错误,xlsx文件对应的MIME类型是
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,而非text/plain。
3. 代码优化点
- 避免用
.Result同步调用异步方法,易引发死锁,改用await实现异步流程。 - 重复创建
HttpClient会导致资源泄漏,建议复用单例实例。
修复后的代码
using System.Net.Http.Headers; using System.IO; // Upload files to SharePoint public async Task SharePointUploadDriveItemsAsync(string accessToken) { // 建议全局复用HttpClient实例,避免重复创建 using var client = new HttpClient(); try { string filePath = @"C:\StockLevelReportLocation\New Files\TestFileUpload.xlsx"; byte[] fileBytes = File.ReadAllBytes(filePath); string fileName = Path.GetFileName(filePath); // 修正后的Graph API请求地址 string requestUri = "https://graph.microsoft.com/v1.0/drives/root:/Oks/Stock Report/TestFileUpload.xlsx:/content"; using var request = new HttpRequestMessage(HttpMethod.Put, requestUri); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // 直接传入文件字节数组,设置正确的MIME类型 request.Content = new ByteArrayContent(fileBytes); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); HttpResponseMessage response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); // 主动抛出HTTP状态错误 string responseContent = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { throw new Exception($"文件上传失败: {ex.Message}", ex); } }
额外验证步骤
- 确认
Oks文件夹确实存在于Drive根目录,路径名称无拼写错误(Graph API路径区分大小写)。 - 确保accessToken拥有
Files.ReadWrite(个人Drive)或Sites.ReadWrite.All(SharePoint站点Drive)的权限。
内容的提问来源于stack exchange,提问作者KSampath
相关产品推荐
相关产品推荐

