任务不包含内容

时间:2018-03-05 02:12:01

标签: c# asp.net xamarin xamarin.forms

如何克服下面的错误? 我已经按照下面的教程进行操作,但是我得到的红线表示不包含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

  

'任务'不包含'内容'的定义没有扩展方法'内容'接受类型'任务'的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)

这是错误但有任何想法要解决它吗?

我已添加此 Microsoft.AspNet.WebApi.Client 程序包但仍然失败

1 个答案:

答案 0 :(得分:3)

使事件处理程序异步,然后等待返回Task派生结果的函数,因为在调用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();
}

请注意,事件处理程序是允许async void的规则的例外

参考Async/Await - Best Practices in Asynchronous Programming