问题
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();
}
'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
回答1:
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
来源:https://stackoverflow.com/questions/49102545/task-does-not-contain-a-definition-for-content