C#-如何检查用户是否使用HttpWebRequest登录到Web [英] C# - How to check if a user logged in into a web using HttpWebRequest
本文介绍了C#-如何检查用户是否使用HttpWebRequest登录到Web的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经使用 HttpWebRequest 编写了一个C#函数,该函数检查用户是否成功登录到网络以及该用户登录所花费的时间(以毫秒为单位). 问题是,即使我使用了尝试捕获功能,但是当我输入错误的用户名和密码时,它仍然无法捕获,并且我无法验证它是否成功. 如何检查用户是否成功登录?
I have written a C# function using HttpWebRequest that checks if a user successfully logged in to a web and how much time in Milliseconds it took him to log in. The problem is, that even though I used try and catch, when I enter the wrong Username and Password it's still not going to catch and I can't verify if it succeeded. How can I check if the user actually logged in successfully?
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用于未经授权的响应.
You should use below code to get status of response , responseCode 401 is for unauthorized response.
var isInvalidAccess = resp.StatusCode == HttpStatusCode.Unauthorized;
这篇关于C#-如何检查用户是否使用HttpWebRequest登录到Web的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文