Allen King
Allen King

Reputation: 2516

Box.Net Create Folder Bad Request 400

Dim url As String = String.Format("{0}folders/{1}", boxApiUrl, ParentFolderId)  'ParentFolderId being pass is "0"
    Using request = New HttpRequestMessage() With {.RequestUri = New Uri(url), .Method = HttpMethod.Post}
        request.Headers.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Bearer " + acctoken)

       Dim data As Dictionary(Of [String], [String]) = New Dictionary(Of String, String)()
       data.Add("name", FolderName)

       Dim content As HttpContent = New FormUrlEncodedContent(data)
       request.Content = content
       Dim response = _httpClient.SendAsync(request).Result
       If response.IsSuccessStatusCode Then
                '        
       End If
    End Using

My suspicion is that data is not being put together properly but can't figure out how else to pass folder name to be created under the root. All other functions (reading root folder, uploading file, etc.) using the token works fine.

Upvotes: 0

Views: 352

Answers (1)

John Hoerr
John Hoerr

Reputation: 8025

The parent folder ID is passed in the POST body, not the URL. The body should be JSON data in the form: { "name": "FolderName", "parent": { "id": "ParentFolderId" }}. Documentation.

Dim url As String = String.Format("{0}folders", boxApiUrl)
Using request = New HttpRequestMessage() With {.RequestUri = New Uri(url), .Method = HttpMethod.Post}
    request.Headers.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Authorization", "Bearer " + acctoken)

   Dim format as String = @"{{ ""name"":""{0}"", ""parent"": {{ ""id"":""{1}"" }} }}";
   Dim body as String = String.Format(format, FolderName, ParentFolderId);
   request.Content = New StringContent(body, Encoding.UTF8, "application/json")

   Dim response = _httpClient.SendAsync(request).Result
   If response.IsSuccessStatusCode Then
            '        
   End If
End Using

As an aside, you can use Json.NET's JsonConvert.SerializeObject method to serialize an anonymous or static type to a JSON string:

Dim obj = New With {Key .name = FolderName, 
                        .parent = New With {Key .id = ParentFolderId }};
Dim body as String = JsonConvert.SerializeObject(body);
request.Content = New StringContent(body, Encoding.UTF8, "application/json")

Upvotes: 1

Related Questions