c# - 任务不包含内容的定义

标签 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

'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?)

这是错误,但有解决办法吗?

我已经添加了这个 Microsoft.AspNet.WebApi.Client 包,但仍然失败

最佳答案

使事件处理程序异步,然后等待返回任务派生结果的函数,因为您在调用 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 的规则的异常(exception)

引用 Async/Await - Best Practices in Asynchronous Programming

关于c# - 任务不包含内容的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49102545/

相关文章:

asp.net - 为其他网站存储 cookie

c# - 代码应在短暂延迟后执行一次

c# - 尝试向 Azure 通知中心注册 Xamarin 应用程序时出现未经授权的异常

c# - 使用带有 Xamarin Mac 的 Controller 打开窗口

c# - 访问当前在 Outlook 2007 中选择的文本

c# - 通用工厂问题、运行时转换和协变/逆变问题

c# - 有没有更优雅的方法使用 system.text.json 从 JSON 对象获取特定值

c# - 在 WebAPI 客户端中每次调用创建一个新的 HttpClient 的开销是多少?

.net - 关于让 Sitefinity CMS 以中等信任度工作的任何提示?

c# - HttpResponseException 不接受 HttpStatusCode