c# - 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;
}
解决方案
您应该使用以下代码来获取响应状态, responseCode 401 用于未经授权的响应。
var isInvalidAccess = resp.StatusCode == HttpStatusCode.Unauthorized;
推荐阅读
- java - 访问 jar 中的 Json 文件时 (java.lang.NullPointerException)
- javascript - 有没有办法用已经将其转换为下划线来替换不是某个字符的所有字符
- c - 使用 rand() 的高斯分布
- reactjs - 在 react.js 中导出组件中的对象
- python - 带有 python 入口点的 Google Cloud Build gsutil
- javascript - Vue 3 + typescript:单个文件组件中的类型检查道具
- android - 无法在 android 模拟器上运行 react-native 应用程序,因为 'C:/User/firstname' 未被识别为内部或外部命令
- sql - 计算有多少不同的组合加起来等于某个值
- javascript - 单击时在 div 内水平滚动(带按钮)
- python - 如果条件满足,则将项目添加到列表中,直到该列表达到一定长度(Python)