目录
2.1 背景介绍
在我们学校教务网站的登录系统中,为了防止CSRF攻击,在ASP.NET网站源码中添加了AntiForgeryToken(),所以在表单中有一个隐藏的域"__RequestVerificationToken",因此,在Ajax提交表单时,要注意将其一起提交。
2.2 登录函数代码
因为由于网络环境的不同,当函数运行时,可能网页尚未加载完成,所以编写一个延时函数等待加载完成。
public void Wait(int mis)
{
DateTime now = DateTime.Now;
int s;
do
{
TimeSpan spand = DateTime.Now - now;
s = spand.Seconds;
Application.DoEvents();
}
while (s < mis);
}
下面是登录函数的代码。
构造一个script标签编写函数,函数内容为发送Ajax请求提交账号密码,这里我选择了用*代替具体的账号密码和学校网址,可以按情况修改。必要时还可以通过textbox获取。
用webBrowser1.Document.Body.AppendChild(HTMLElement e)方法将上面创建的script元素添加到webbrower的body的尾部。
用webBrowser1.Document.InvokeScript(string functionName)方法调用刚刚插入的标签中的函数,即实现登录操作。
public void Login()
{
Wait(1);
HtmlElement script = webBrowser1.Document.CreateElement("script");
script.SetAttribute("type", "text/javascript");
script.SetAttribute("text", "function Mylogin(){var token = $(\"input[name = '__RequestVerificationToken']\").val();$.ajax({type: \"post\",url: 'http://jw.****.edu.cn/m/Account/Login',data: {\"__RequestVerificationToken\":token,\"UserName\":\"******\",\"Password\":\"******\"},success: function() {self.location=\"http://jw.***.edu.cn/m/Personal/CourseList\";}});}");
HtmlElement head = webBrowser1.Document.Body.AppendChild(script);
webBrowser1.Document.InvokeScript("Mylogin");
}
2.3 Ajax请求内容的详细解释
$是JS应用库jQuery中的一个自定义函数名,是获取指定网页元素的函数。上述的用法是属性选择器,即选择指定属性是给定值的元素。查找所有name属性值为 '__RequestVerificationToken' 的 input 元素,当然,它返回的可能不止一个元素,所以用val()方法获取匹配的元素集合中第一个元素的当前value值。并将该值赋给变量token。
var token = $("input[name = '__RequestVerificationToken']").val();
.ajax()是jQuery中执行一个异步的HTTP(Ajax)的请求的函数。在上述的用法里,我构造了一个type为post,url为学校教务网站登录网址,data包括__RequestVerificationToken、UserName、Password,并编写函数,请求成功时,将网页跳转到教务网站的成绩查询页面。
$.ajax({
type: "post",
url: 'http://jw.****.edu.cn/m/Account/Login',
data:
{
"__RequestVerificationToken":token,
"UserName":"*****",
"Password":"*****"
},
success: function() {
self.location="http://jw.***.edu.cn/m/Personal/CourseList";
}
});
当然,由于是在C#语言中调用这些js代码,所以在所有JS中的"前都要加\进行转义。
2.4 结语
通过对Ajax的基本操作,以及构建html标签并添加进webbrower的文档中,调用其函数,实现网站的登录。