Search code examples
c#asp.net-mvcmicrosoft-graph-apihttp-status-code-401onedrive

OneDrive file upload unexpected 401


Im trying to upload a file using the OneDrive API. Authentication works as expected. Authentication uses files.readwrite.all and offline_access scopes. Other calls like getting the files of the users also work as expected. When tring to upload a file I'm getting a 401 unauthorized error.

First I create an upload session and get the upload URL using the code below:

using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri("https://graph.microsoft.com");
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.ToString());

    HttpResponseMessage response;

    response = await client.PostAsync("/v1.0/drive/root:" + path + "/" + file.FileName + ":/createUploadSession", null);


    string uploadUrl = (string)JObject.Parse(await response.Content.ReadAsStringAsync())["uploadUrl"];
}

This works as expected. The response status code is 200 and I get the upload URL. Next I want to upload the file using the upload URL. The content contains the bytes of the first chunk I want to upload. Content-Length and Content-Range are also set correctly. I'm sending the content using the same client to the upload URL using a put request.

ByteArrayContent content = new ByteArrayContent(chunk);
content.Headers.Add("Content-Length", (contentRangeEnd - contentRangeBegin).ToString());
content.Headers.Add("Content-Range", "bytes " + contentRangeBegin + "-" + (contentRangeEnd - 1) + "/" + allBytes.Length);

response = await client.PutAsync(uploadUrl, content);

The put request results in a 401 error. The access token seems to be valid because other calls like getting the files work as expected.

How do I resolve the 401 error?


Solution

  • Try removing the authorization header (Bearer + access token) from the chunk upload Put request. It is not required by Graph API and maybe it is causing the issue.