Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task does not contain a definition for Content

How to overcome the error below? I have follow below tutorial but I get the red line that state that does not contain definition of Content. https://www.youtube.com/watch?v=IVvJX4CoLUY

private void UploadFile_Cliked(object sender, EventArgs e)
{
    var content = new MultipartFormDataContent();
    content.Add(new StreamContent(_mediaFile.GetStream()),
        "\"file\"",
        $"\"{_mediaFile.Path}\"");
    var httpClient = new HttpClient();

    var uploadServiceBaseAddress = "http://192.168.137.1/pic/";
    var httpResponseMessage = httpClient.PostAsync(uploadServiceBaseAddress, content);
    RemotePathLabel.Text = httpResponseMessage.Content.ReadAsStringAsync();
}

enter image description here

'Task' does not contain a definition for 'Content' and no extension method 'Content' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?)

This is the error but any idea to solve it?

I have add this Microsoft.AspNet.WebApi.Client package but still fail

like image 983
Shi Jie Tio Avatar asked Oct 17 '22 21:10

Shi Jie Tio


1 Answers

Make the event handler async and then await functions that return Task derived results as you would have ended up with the same problem when calling ReadAsStringAsync

private HttpClient httpClient = new HttpClient();

private async void UploadFile_Cliked(object sender, EventArgs e) {
    var content = new MultipartFormDataContent();
    content.Add(new StreamContent(_mediaFile.GetStream()),
        "\"file\"",
        $"\"{_mediaFile.Path}\"");        

    var uploadServiceBaseAddress = "http://192.168.137.1/pic/";
    var httpResponseMessage = await httpClient.PostAsync(uploadServiceBaseAddress, content);
    RemotePathLabel.Text = await httpResponseMessage.Content.ReadAsStringAsync();
}

Note that event handlers are an exception to the rule where async void are allowed

Reference Async/Await - Best Practices in Asynchronous Programming

like image 146
Nkosi Avatar answered Oct 27 '22 00:10

Nkosi