任务不包含内容的定义 [英] Task does not contain a definition for Content

查看:92
本文介绍了任务不包含内容的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何克服以下错误?我已经按照下面的教程进行操作,但是我得到的红线指出的是其中不包含 Content 的定义.

任务"不包含内容"的定义,也找不到找不到接受任务"类型的第一个参数的扩展方法内容"(您是否缺少using指令或程序集引用?)

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

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

解决方案

使事件处理程序异步,然后等待返回Task派生结果的函数,就像调用 ReadAsStringAsync

  private HttpClient httpClient = new HttpClient();私人异步void UploadFile_Cliked(object sender,EventArgs e){var content = new MultipartFormDataContent();content.Add(新的StreamContent(_mediaFile.GetStream()),\文件\"",$"\" {_ mediaFile.Path} \");var uploadServiceBaseAddress ="http://192.168.137.1/pic/";var httpResponseMessage =等待httpClient.PostAsync(uploadServiceBaseAddress,content);RemotePathLabel.Text =等待httpResponseMessage.Content.ReadAsStringAsync();} 

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

参考异步/等待-异步编程的最佳做法

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

解决方案

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

这篇关于任务不包含内容的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆