1

所以我试图让一个页面提交给自己,然后在出错时重定向回自己,或者在成功时重定向到其他地方。

我有在 VB.NET 中工作的示例代码,但我试图让相同的代码在 C# 中工作。我觉得错误在于使用 Page_Load - 我觉得我应该使用另一个调用。

由于现在的代码,我得到一个无限重定向循环,这是不可接受的。

这是代码:

<% @Page Language="C#" Debug="true" %>
<% @Import Namespace="System.Web" %>
<script language="C#" runat="server">
    void Page_Load(object sender,EventArgs e) {
        if( Request.Form["username"] == "admin" && Request.Form["password"] ==  "password") {
            HttpContext.Current.Session["username"] = Request.Form["username"];
            HttpContext.Current.Session["password"] = Request.Form["password"];
            Response.Redirect("elsewhere.html");
        }
        else {
            Response.Redirect("login.aspx?errors=1");
        }
    }
</script>

<!-- #include file="header.html" -->

<form action="" method="post">
    <div id="errors">Incorrect Username or Password</div>
    <div><span>Username:</span><input name="username" /></div>
    <div><span>Password:</span><input name="password" type="password" /></div>
    <div><input type="button" value="Login" id="loginbutton" /></div>
</form>

<!-- #include file="footer.html" -->

谢谢!

4

2 回答 2

2

我想你不见了

if (IsPostBack) {
   //Your code here
}

这将允许您的代码仅在表单刚刚提交时触发。

于 2012-05-22T17:17:52.820 回答
1

无限重定向的原因是

 Response.Redirect("login.aspx?errors=1");

与第一次加载页面时一样, Request.Form["username"] == "admin" 并且任何这些条件都会导致 else 部分执行。它一次又一次地无限加载 login.aspx。

当页面回发时,我们将这些语句执行。你的代码是。

if(Page.IsPostBack)
{
    if( Request.Form["username"] == "admin" && Request.Form["password"] ==  "password") {
                HttpContext.Current.Session["username"] = Request.Form["username"];
                HttpContext.Current.Session["password"] = Request.Form["password"];
                Response.Redirect("elsewhere.html");
            }
            else {

                    Response.Redirect("login.aspx?errors=1");
            }
}
于 2012-05-22T17:19:08.903 回答