C#控制台应用程序意外关闭

时间:2019-06-04 23:21:34

标签: c# asynchronous httpclient

我正在尝试为控制台应用程序编程一种基本的身份验证方法,但是似乎在输入时意外关闭了。

代码示例-

    private static async Task Auth()
    {
        try
        {

            Console.WriteLine("Verify authentication");
            Console.WriteLine("Enter your 6 digit code: ");
            string AuthenticationKey = Console.ReadLine();

            if (AuthenticationKey != "")
            {

                using (HttpClient client = new HttpClient())
                {
                    using (HttpResponseMessage response = await client.GetAsync("http://www.anysiteexample.com"))
                    {
                        using (HttpContent content = response.Content)
                        {

                            string result = await content.ReadAsStringAsync();

                            if(result.Contains(AuthenticationKey))
                            {

                                Console.WriteLine("Successfully validated credentials, starting program...");
                                Setup();

                            }
                            if(!result.Contains(AuthenticationKey))
                            {
                                Console.WriteLine("Failed");
                                await Auth();
                            }

                        }
                    }
                }

            }
            if (AuthenticationKey == "")
            {

                Console.WriteLine("Auth key is empty");
                await Auth();

            }
        }
        catch(Exception)
        {
            Console.WriteLine("Error raised closing application...");
            Thread.Sleep(5000);
            Environment.Exit(0);
        }
    }

如果我在Console.ReadLine()上不输入任何内容,则它将成功执行else语句,但是,如果我在Console.ReadLine()上输入任何字母数字,它将毫无例外地意外关闭?总的来说,它应该处理httpclient请求,然后处理其中的if / else语句之一。

2 个答案:

答案 0 :(得分:1)

我不适应新的async-不带Task的速度(是否有事?以为是C#8中发生的事情),但是您正在递归调用{ {1}},Auth()操作,没有等待,因此原始线程正在退出。尝试等待这些递归调用(如果这不是新功能,则返回Task,例如@zhulien说)

但是实际上,您不应该在这里进行递归调用-您应该返回false(也许带有解释),如果需要的话,让调用代码向async发出另一个调用。

答案 1 :(得分:1)

我认为最好避免递归调用,而只使用while循环来验证键输入:

async void Auth()
{
    try
    {
        string authenticationKey = null;
        while(string.IsNullOrEmpty(authenticationKey))
        {
            Console.WriteLine("Verify authentication");
            Console.WriteLine("Enter your 6 digit code: ");
            authenticationKey = Console.ReadLine();

            if (string.IsNullOrEmpty(authenticationKey))
            {
                Console.WriteLine("Auth key is empty");
                continue;
            }

            if (!await IsAuthenticated(authenticationKey))
            {
                Console.WriteLine("Failed to validate credentials.");
                authenticationKey = null;
                continue;
            }

            break;
        }

        Console.WriteLine("Successfully validated credentials, starting program...");
        Setup();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error raised closing application: {ex.Message}");
        Thread.Sleep(5000);
        Environment.Exit(0);
    }
}

async Task<bool> IsAuthenticated(string key)
{
    if (string.IsNullOrEmpty(key))
        return false;

    using (HttpClient client = new HttpClient())
    using (HttpResponseMessage response = await client.GetAsync("http://www.authentication.com/example"))
    using (HttpContent content = response.Content)
    {
        string result = await content.ReadAsStringAsync();
        return result.Contains(key);
    }
}