首页 > 解决方案 > C# - 如何检查用户是否使用 HttpWebRequest 登录到网络

问题描述

我已经使用HttpWebRequest编写了一个 C# 函数,该函数检查用户是否成功登录到网络以及他登录所需的时间(以毫秒为单位)。问题是,即使我使用了 try 和 catch,当我输入错误时用户名和密码仍然无法捕获,我无法验证它是否成功。如何检查用户是否实际登录成功?

private int[] LoginCheck(string TargetWebApp)
        {
            int[] result = new int[2];
            var watch = System.Diagnostics.Stopwatch.StartNew();
            try
            {


                string formUrl = "https://XXXXX.com/user/login/default"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
                string formParams = string.Format("email_address={0}&password={1}", "XXXXX", "XXXXX");
                string cookieHeader;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(formUrl);
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
                req.ContentType = "application/x-www-form-urlencoded";
                req.Method = "POST";
                byte[] bytes = Encoding.ASCII.GetBytes(formParams);
                req.ContentLength = bytes.Length;
                using (Stream os = req.GetRequestStream())
                {
                    os.Write(bytes, 0, bytes.Length);
                }
                HttpWebResponse resp = req.GetResponse() as HttpWebResponse;;
                var elapsedMs = watch.ElapsedMilliseconds;
                watch.Stop();
                Console.WriteLine("Login to WebApp succeed in {0} Milliseconds", elapsedMs);
                cookieHeader = resp.Headers["Set-cookie"];
                result[0] = 1;
                result[1] = (int)elapsedMs;

            }
            catch (Exception e)
            {
                //Any exception will return false.
                Console.WriteLine(e.Message);
                result[0] = 0;
                result[1] = 0;
            }

            return result;
        }

标签: c#httptestingwebhttpwebrequest

解决方案


您应该使用以下代码来获取响应状态, responseCode 401 用于未经授权的响应。

var isInvalidAccess = resp.StatusCode == HttpStatusCode.Unauthorized;

推荐阅读