Skip to main content
Box Employee
May 27, 2025 10:47 AM UTC
Question

Upload a File - Rest API - C#

I'm trying to use .net core 3, to invoke the Box REST API, to upload a small file.

The .net core code is based on the information provided on: Upload a file.

I haven't been successful so far, and all my attempts have resulted in a 400: Bad Request error.

 

This is code snippet:

 

var client = _clientFactory.CreateClient("box-upload");

var dto = new UploadFileContent() {
 attributes = new UploadFileContentAttributes() {
  name = fileDto.file.FileName,
   parent = new UploadFileContentParent() {
    id = fileDto.folderId
   }
 }
};
var content = new MultipartFormDataContent();
content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

var jsonContent = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
jsonContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
content.Add(jsonContent, "attributes");

if (!string.IsNullOrWhiteSpace(token))
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(BearerToken, token);

var streamContent = new StreamContent(fileDto.file.OpenReadStream());
content.Add(streamContent, "file");

var response = await client.PostAsync(url, content);

 

What am i missing?

Thank you in advance.

 

 

    1 reply

    Box Employee
    May 27, 2025 10:47 AM UTC

    There were a few details missing, the code is now working:

     

     

    var token = await GetToken();
    
    if (string.IsNullOrWhiteSpace(token)) throw new Exception("Could not obtain Token");
    
    var client = _clientFactory.CreateClient("box-upload");
    
    using var content = new MultipartFormDataContent();
    var attributes = new UploadFileContentAttributes {
     name = fileDto.file.FileName,
      parent = new UploadFileContentParent {
       id = fileDto.folderId
      }
    };
    
    using var jsonContent =
     new StringContent(JsonConvert.SerializeObject(attributes), Encoding.UTF8, "application/json");
    content.Add(jsonContent, "attributes");
    
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(BearerToken, token);
    
    byte[] data;
    using(var br = new BinaryReader(fileDto.file.OpenReadStream())) {
     data = br.ReadBytes((int) fileDto.file.OpenReadStream().Length);
    }
    
    using var bytes = new ByteArrayContent(data);
    
    content.Add(bytes, "file", fileDto.file.FileName);
    
    var response = await client.PostAsync(url, content);
    
    if (!response.IsSuccessStatusCode) throw new Exception(response.ToString());
    
    var jsonString = await response.Content.ReadAsStringAsync();

     

    Translate