await HttpClient.PostAsync method compilation error
本问题已经有最佳答案,请猛点这里访问。
我试图用以下代码发出一个POST请求:
1 2 3 4 5 | string resourceAddress ="url"; string postBody ="jsonbody"; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage x = await httpClient.PostAsync(resourceAddress, new StringContent(postBody, Encoding.UTF8,"application/json")); |
我得到这个编译错误:"await"运算符只能在异步方法中使用
有什么想法吗?PostAsync返回
您的方法必须标记为
1 2 3 4 5 6 7 8 | public async ReturnType MethodName() { string resourceAddress ="url"; string postBody ="jsonbody"; var httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage x = await httpClient.PostAsync(resourceAddress, new StringContent(postBody, Encoding.UTF8,"application/json")); } |
不知道方法的返回类型,也不知道方法名及其参数,我使用了模糊的名称,没有参数。你必须用真正的代替它们。
一般来说,只要您想使用