Task does not contain a definition for Content

我们两清 提交于 2021-02-08 15:17:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!