C#-如何检查用户是否使用HttpWebRequest登录到web
我已经使用HttpWebRequest编写了一个C#函数,用于检查用户是否成功登录到web,以及登录所用的时间(毫秒)。 问题是,即使我使用了try-and-catch,当我输入错误的用户名和密码时,它仍然无法捕获,并且我无法验证它是否成功。 如何检查用户是否确实成功登录C#-如何检查用户是否使用HttpWebRequest登录到web,c#,http,testing,web,httpwebrequest,C#,Http,Testing,Web,Httpwebrequest,我已经使用HttpWebRequest编写了一个C#函数,用于检查用户是否成功登录到web,以及登录所用的时间(毫秒)。 问题是,即使我使用了try-and-catch,当我输入错误的用户名和密码时,它仍然无法捕获,并且我无法验证它是否成功。 如何检查用户是否确实成功登录 private int[] LoginCheck(string TargetWebApp) { int[] result = new int[2]; var wa
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;
}
您应该使用下面的代码来获取响应状态,响应代码401用于未经授权的响应
var isInvalidAccess = resp.StatusCode == HttpStatusCode.Unauthorized;
您应该使用下面的代码来获取响应状态,响应代码401用于未经授权的响应
var isInvalidAccess = resp.StatusCode == HttpStatusCode.Unauthorized;
你确定你输入的是张贴的代码吗?是的,怎么了?没有。您没有得到任何异常,您得到的是响应。所以你应该输出时间。当您输入错误的密码时,您的状态为401,这是预期的响应。您确定您输入的是发布的代码吗?是的,有什么问题?没有。您没有得到任何异常,您得到的是响应。所以你应该输出时间。当您输入错误的密码时,您得到的状态是401,这是预期的响应。为什么resp.StatusCode是invaild?可能resp对象没有此属性?请使用此((HttpWebResponse)resp)。状态代码谢谢,但我将WebRequest改为HttpWebRequest。无论如何,当登录成功和失败时,它仍然显示isInvalidAccess=false(如两次..)resp.StatusCode=Ok在提供错误的密码后,您的web响应是Ok的。这意味着您需要修复并发送401。为什么resp.StatusCode是invaild?可能resp对象没有此属性?请使用此((HttpWebResponse)resp)。状态代码谢谢,但我将WebRequest改为HttpWebRequest。无论如何,当登录成功和失败时,它仍然显示isInvalidAccess=false(如两次..)resp.StatusCode=Ok在提供错误的密码后,您的web响应是Ok的。这意味着你需要修复并发送401。