在webapi中异步和等待 [英] Async and await in webapi

查看:355
本文介绍了在webapi中异步和等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有以下代码,我将从服务器上托管的WebAPI获取日期时间。

但是当我尝试代码时,它会返回错误消息:

任务字符串不包含getawaiter的定义,也没有扩展名.......



Hi I have the following codes in which I will get datetime from a WebAPI that is hosted on a server.
But when I try out the codes, it returns me the error message:
task string does not contain a definition for getawaiter and no extension.......

public async void RegenerateServerDate()
{
    DateTime dateTime = new DateTime();
    
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://localhost:8080");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //error message here
        HttpResponseMessage response = await client.GetAsync("api/servertime");
        if (response.IsSuccessStatusCode)
        {
            //error message here
            string result = await response.Content.ReadAsStringAsync();
            result = Regex.Replace(result, @"[A-Za-z\]""", "");
            dateTime = DateTime.Parse(result);
        }
    }

}





我尝试过:



1.厌倦了创建另一个WindowForm并将上述代码应用到按钮点击事件中。运行良好且没有错误。



What I have tried:

1. Tired by creating another WindowForm and apply the above codes into a button click event. Runs well without error.

推荐答案

您可能会看到此错误消息的多种可能性,请看一下:

< a href =http://stackoverflow.com/questions/11853812/task-does-not-contain-a-definition-for-getawaiter>

任务 - 不包含 - a -definition-for-getawaiter





希望有所帮助。
There are multiple possibilities why you are seeing this error message, please take a look at this :

task-does-not-contain-a-definition-for-getawaiter


Hope it helps.


这篇关于在webapi中异步和等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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