繁体   English   中英

C#-如何检查用户是否使用HttpWebRequest登录到网络

[英]C# - How to check if a user logged in into a web using HttpWebRequest

我已经使用HttpWebRequest编写了一个C#函数,该函数检查用户是否成功登录到Web以及登录该用户花了多少毫秒。问题是,即使我使用try and 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;
        }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM