Search code examples
c#apimicrosoft-graph-apionedrive

Microsoft graph api create folder using path returning 'invalidRequest'


The following error is returned by graph api:

  "error": {
"code": "invalidRequest",
"message": "[child] A null value was found for the property named 'id', which has the expected type 'Edm.String[Nullable=False]'. The expected type 'Edm.String[Nullable=False]' does not allow null values.",
"innerError": {
  "request-id": "36d65bbb-2f6e-485c-b2b9-5bb7fdb76d19",
  "date": "2017-09-30T00:24:06"
  }
}

The code I'm using:

var url = "https://graph.microsoft.com/v1.0/me/drive/root:/joba:/children";
var folder = new ItemResource { name = "nested", folder = new FolderFacet() };
var response = api.PostAsJsonAsync<ItemResource>(url, folder).Result;
response.ThrowWhenUnsuccessful();
return response.Content.ReadAsAsync<ItemResource>().Result;

That is, I'm trying to create a nested folder named nested in the joba folder (which is inside root). It doesn't work... I even tried to escape the colon :joba: but it doesn't work either. The same request works just fine in graph-explorer

What is wrong with mine?

EDIT Fiddler request

POST https://graph.microsoft.com/v1.0/me/drive/root:/wdg:/children HTTP/1.1
Accept: application/json
Authorization: Bearer <OMITED>
Content-Type: application/json; charset=utf-8
Host: graph.microsoft.com
Content-Length: 268
Expect: 100-continue
Connection: Keep-Alive

{"id":null,"createdBy":null,"createdDateTime":null,"eTag":null,"cTag":null,"description":null,"lastModifiedBy":null,"lastModifiedDateTime":null,"name":"85923635-56af-4902-82da-babd95165c6b","parentReference":null,"webUrl":null,"folder":{"ChildCount":null},"file":null}

Solution

  • PostAsJsonAsync uses Json.NET under the covers, which by default will serialize properties with null values. Since omitting a value is treated differently to deliberately specifying a null value, when this occurs it triggers the OneDrive API to consider the request invalid, because a null value is specified for a non-nullable field.

    To get around this you can add the following attribute to the nullable properties on the ItemResource type:

    [JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
    

    Alternatively, you could use Json.NET to directly serialize the object and provide an appropriately configured JsonSerializerSettings instance, followed by a call to PostAsync.