Skip to main content
 首页 » 编程设计

c#之WebApi 核心项目调试卡在 await client.GetAsync 上

2024年01月29日25zengkefu

我有 2 个项目的解决方案:Asp.Net WebApi Core 和 WinForms。我将使用来自 WinForm 的服务。

更改解决方案属性以启动多个项目:第一个 WebApi,然后是 WinForm(主窗体是 FORM1)。

现在,我有如下简单的代码:

private void button1_Click(object sender, EventArgs e) 
{ 
    TestAutentication().Wait(); 
    Console.ReadKey(); 
} 
 
static async Task TestAutentication() 
{ 
    HttpClientHandler handler = new HttpClientHandler(); 
    handler.UseDefaultCredentials = true; 
    using (var client = new HttpClient(handler)) 
    { 
 
        client.BaseAddress = new Uri("http://localhost:53791"); 
 
        try 
        { 
            HttpResponseMessage response = await client.GetAsync("api/ValuesController"); 
            if (response.IsSuccessStatusCode) 
            { 
                var result = await response.Content.ReadAsAsync<string>(); 
                Console.WriteLine("{0}", result); 
            } 
            else 
            { 
                Console.WriteLine("{0}", response.ReasonPhrase); 
            } 
 
        } 
        catch (HttpRequestException ex) 
        { 
            Console.WriteLine("{0}", ex.Message); 
        } 
 
    } 
} 

在启动期间浏览器打开,然后打开 FORM1。单击 button1 调试器在执行该行时挂起:

HttpResponseMessage response = await client.GetAsync("api/ValuesController");

挂起的原因可能是什么?

提前致谢。

请您参考如下方法:

您通过在任务上调用 .Wait() 使主线程陷入死锁。您需要像这样在堆栈中一直等待任务:

private async void button1_Click(object sender, EventArgs e) 
{ 
    await TestAutentication(); 
    Console.ReadKey(); 
} 

关于 async void 注释,它们通常是一种代码味道,应该避免,但是当用于事件处理程序时就可以了。

引用: Should I avoid 'async void' event handlers?