You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MS Graph API PUT请求错误:仅允许JSON Content-Type头写入实体

问题分析与解决方案

原代码存在的问题

  • API路径拼写错误:请求URL末尾的:/conten应为:/content,少写了字母t,导致请求到错误端点。
  • Content-Type配置错误:
    • 上传二进制文件(如Excel)时,不应将ContentType添加到请求Headers,而应设置请求内容的媒体类型,且需匹配Excel文件的MIME类型application/vnd.openxmlformats-officedocument.spreadsheetml.sheet。
    • 原代码把二进制文件转成Base64再解码为ASCII字符串,这会破坏二进制数据(ASCII无法完整表示所有字节),且用text/plain作为Content-Type不符合Graph API要求。
  • 异步调用不当:使用.Result阻塞调用可能引发死锁,应采用async/await模式。
  • 异常处理语法错误:throw new Exception(Exception - " + ex.ToString());字符串拼接缺少前引号,语法无效。

修正后的代码

// Upload files to SharePoint
public async Task SharePointUploadDriveItemsAsync(string accessToken, string driveId)
{
    try
    {
        string path = @"C:\StockLevelReportLocation\New Files\TestFileUpload.xlsx";
        byte[] filebytes = System.IO.File.ReadAllBytes(path);

        using (var httpClient = new HttpClient())
        {
            // 修正API路径拼写错误
            var requestUrl = $"https://graph.microsoft.com/v1.0/drives/{driveId}/root:/Oks/Stock Report/TestFileUpload.xlsx:/content";
            using (var request = new HttpRequestMessage(HttpMethod.Put, requestUrl))
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                
                // 直接传递二进制文件,设置正确的Excel MIME类型
                request.Content = new ByteArrayContent(filebytes);
                request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

                // 使用async/await避免死锁
                var driveItemsResponse = await httpClient.SendAsync(request);
                driveItemsResponse.EnsureSuccessStatusCode(); // 主动抛出HTTP请求错误
                var driveItemsResponseContent = await driveItemsResponse.Content.ReadAsStringAsync();
            }
        }
    }
    catch (Exception ex)
    {
        // 修正字符串拼接错误
        throw new Exception("Exception - " + ex.ToString());
    }
}

关键说明

  1. 路径修正:确保API路径为:/content,这是Graph API上传文件内容的正确端点。
  2. 内容类型设置:用ByteArrayContent直接传递二进制文件,设置Excel对应的MIME类型,让Graph API正确识别文件格式。
  3. 异步优化:改用async/await处理异步请求,避免阻塞导致的死锁问题。
  4. 错误处理:添加EnsureSuccessStatusCode()可在HTTP请求失败时直接抛出异常,便于调试定位问题。

内容的提问来源于stack exchange,提问作者KSampath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 03:26:02