今天在一ASP.NET站上也有类似的流程,但却总出错,研究了下,下边是简化了的代码:
checkuser.aspx:
<script runat="server">
Function checkuser()
If Session("username") = Nothing Then
Response.Redirect("login.aspx")
End If
End Function
</script>
<%
checkuser()
%>Manage.aspx:
<%@ Page Language="VB" %>
<!-- #include file="checkuser.aspx" -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
'正常登录后的操作
Response.Write("当前用户:" + Session("username").ToString())
End Sub
Sub Page_Unload(ByVal Sender As Object, ByVal E As EventArgs)
'
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>测试-Mzwu.Com</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>奇怪的是不仅没有跳转到login.aspx页,反而是页面发生了错误"未将对象引用设置到对象的实例"!原因是Session("username")为空值,使用ToString()导致出错!<!-- #include file="checkuser.aspx" -->不是放在最前边了,怎么没像ASP那样发生作用呢?其实原因也很简单:ASP.NET和ASP有个很大不同的地方,就是有了Page_Load等事件,Page_Load在页面一打开就触发了,它里面的代码比页面中其他代码都先执行!所以在上边的例子中应是先执行了Page_Load,再执行checkuser(),这就不难解释为什么没有跳转反而出错了。知道了原因稍加修改即可:
checkuser.aspx:
<script runat="server">
Function checkuser()
If Session("username") = Nothing Then
Response.Redirect("login.aspx")
End If
End Function
</script>Manage.aspx:
<%@ Page Language="VB" %>
<!-- #include file="checkuser.aspx" -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
checkuser()
'正常登录后的操作
Response.Write("当前用户:" + Session("username").ToString())
End Sub
Sub Page_Unload(ByVal Sender As Object, ByVal E As EventArgs)
'
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>测试-Mzwu.Com</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
评论(0)
暂无评论。