已经CheckUser了为什么还出错?

在需授权才能访问的页面中一般都有相关的程序做身份验证,在ASP中通常是将身份验证的程序单独放在一个文件中,然后在需授权的页面顶部调用这个文件进行验证身份,身份验证失败后就跳转到一指定的页面中(如登录页)。

今天在一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 | 引用: 0 | 查看次数: 3742
发表评论
登录后再发表评论!