Can't upload attachment to task using C#, receiving "file: File is not an object"

Hello,

I’m using a C# .NET Core MVC web app to create/update tasks. One last feature I’m building out is to attach a file to a task.

Here is my C# code:

using var client = new HttpClient();

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_token}");

var uri = _configuration.GetValue<string>("Asana:TaskUri");
uri += string.Format("/{0}/attachments", task.TaskGid);

byte[] bytes = await System.IO.File.ReadAllBytesAsync(fileName);

var content = new MultipartFormDataContent(Guid.NewGuid().ToString())
{
{ new ByteArrayContent(bytes), "\"file\"" }
};

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

var responseString = await response.Content.ReadAsStringAsync();

Executing the above code and passing a PDF file always results in a “file: File is not an object” error, and I can’t seem to figure out why.

Here is the JSON response:

{"errors":[{"message":"file: File is not an object","help":"For more information on API status codes and how to handle them, read the docs on errors: https://developers.asana.com/docs/errors"}]}

Does anyone have any suggestions what I’m doing wrong?

Thank you!

Ok, it’s VB not C# but it’s the same framework you’ll understand.
Oh you’re using “core”, I think webclient is also available.

Dim wc As New Net.WebClient
wc.Headers.Add("Authorization: Bearer " & token)
url = “https://app.asana.com/api/1.0/tasks/” & idTask & “/attachments”
resp = wc.UploadFile(url, fileName)
wc.Dispose()

I ended up using RestSharp and it worked right away…

var request = new RestRequest(Method.POST);
request.AddFile("file", filePath);
IRestResponse response = await client.ExecuteAsync(request);
2 Likes