C#无法在API控制器上调试异步方法

时间:2018-10-23 21:48:28

标签: c# async-await

我要调试的ApiController上有一个方法。此方法使用SendAsync调用外部API。拨打电话后,调试结束。过去在使用控制台应用程序时遇到过类似的问题。我能够通过使用wait()来解决它。如果我错了,请纠正我,但我不相信您要在Web应用程序中执行此操作。

        var msg = new HttpRequestMessage(HttpMethod.Post, url);
        var login = new LoginModel() { username = "test", password = "test" }; 

        msg.Content = new ObjectContent<LoginModel>(login, new JsonMediaTypeFormatter(), (MediaTypeHeaderValue)null);

        //Debugger exits after calling this line.
        var result = await WebApiApplication.HttpClientInstance.SendAsync(msg); 

        //Debugger never gets here. 
        if (result.IsSuccessStatusCode)
        {
            var response = await result.Content.ReadAsStringAsync(); 
        }

我通过使用Web浏览器浏览该方法来调用它。为了完全调试此方法,我需要做什么?

1 个答案:

答案 0 :(得分:0)

也许可以试一试,看看发生了什么?

        var msg = new HttpRequestMessage(HttpMethod.Post, url);
        var login = new LoginModel() { username = "test", password = "test" }; 

        msg.Content = new ObjectContent<LoginModel>(login, new JsonMediaTypeFormatter(), (MediaTypeHeaderValue)null);

        try 
        {
            //Debugger exits after calling this line.
            var result = await WebApiApplication.HttpClientInstance.SendAsync(msg); 

             //Debugger never gets here. 
             if (result.IsSuccessStatusCode)
             {
                var response = await result.Content.ReadAsStringAsync(); 
             }
        }
        catch (Exception ex)
        {
            // do something with the ex.Message;
        }