Search code examples
c#onedrive

400 Error while Uploading files to OneDrive with BITS-Protocol


I try to upload a file to OneDrive via BITS (OneDrive Large File Upload API).

I can create a session, but then when I want to upload the first Fragment, I receive an WebException with a 400 HTTP-Error (Bad request) while reading the response. There are no further information in the exception. My Code is like this:

string requestString = String.Format("https://cid-{0}.users.storage.live.com/items/{1}/{2}", userId, folderId, fileName);

WebRequest webRequest = WebRequest.Create(requestString);
webRequest.Headers.Add("X-Http-Method-Override", "BITS_POST");
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
webRequest.Headers.Add("BITS-Packet-Type", "Fragment");
webRequest.Headers.Add("BITS-Session-Id", sessionId);

webRequest.Headers.Add("Content-Range", String.Format("bytes {0}-{1}/{2}", contentOffset, (contentFragment.Count() + contentOffset), totalContentLength));

webRequest.ContentLength = contentFragment.Count();

webRequest.Method = "POST";


webRequest.GetRequestStream().Write(contentFragment.ToArray(), 0, contentFragment.Count());

WebResponse webResponse = webRequest.GetResponse() as WebResponse;

Here is a screenshot, to see the values for the first request, that is already failing:

enter image description here


Solution

  • We've seen enough questions surrounding how to implement this process that I've created a quick little application that shows how it works. Take a look at the following gist, and see how it compares with what you're actually doing:

    https://gist.github.com/ificator/3460d7b9d0bff74eb0ff