简体   繁体   中英

Form self-submission

So I'm trying to get a page to submit to itself and then redirect either back to itself upon error or elsewhere upon success.

I have example code working in VB.NET, but I'm trying to get the same code to work in C#. I feel like the error is in the use of Page_Load - I feel like I should be using another call.

As the code is now, I get an infinite redirect loop, which is not acceptable.

Here's the code as it is:

<% @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" -->

Thanks!

I think you are missing

if (IsPostBack) {
   //Your code here
}

This will allow your code to only fire if the form has just been submitted.

The reason for infinite redirect is

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

As when the page is loaded for first time Request.Form["username"] == "admin" and any of these condition cause the else portion to execute. Which loads login.aspx again and again infinitely.

We put these statement to execute when page has post back. Your code would be.

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");
            }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM