[英]A login page handling an exception and redirect to another page
我有一個登錄頁面和一個a.cs頁面。
登錄頁面的設計
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="IssueTrak.UserInterface.Login" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtUserName" placeholder="User Name" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="txtPassword" placeholder="Password" TextMode="Password" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnLogin" runat="server" OnClick="btnLogin_Click" Text="Login" />
</div>
</form>
</body>
</html>
並設計了.CS頁面
protected void LoginButton_Click(object sender, EventArgs e)
{
try
{
BusinessLogic objBussinessLogic = new BusinessLogic();
string userName = objBussinessLogic.Authenticate(login,password);
if (!string.IsNullOrEmpty(userName))
{
Session["username"] = userName;
Response.Redirect("Home.aspx",true);
}
else
{
ClientScript.RegisterClientScriptBlock(GetType(), "alert", "alert('Invalid Login.')", true);
}
}
catch (Exception ex)
{
HttpContext.Current.Response.Redirect("Issue.aspx", false);
}
}
}
}
問題是當我輸入數據庫中可用的用戶名和密碼時,它應該返回到Home.aspx,而不是直接捕捉我在哪里弄錯了。 我已將代碼設計為3層體系結構,僅提供了很少的信息,而未提供DB連接部分。 當我輸入正確的憑據時,我只是想重定向到Home.aspx
根據您的代碼和描述,該程序可以正常運行。 您說: when i enter the User name and password that is available in the DB, it should return to Home.aspx
,這實際上將重定向到Home.aspx,因為您輸入了有效的username
和password
,然后說您輸入錯誤的username
和password
,您將不會重定向到Issue.aspx
因為它只是無效的。
如果系統遇到系統異常,則僅將其重定向到Issue.aspx,因為您將代碼放在catch塊中:
catch (Exception ex)
{
HttpContext.Current.Response.Redirect("Issue.aspx", false);
}
Response.Redirect("something", true)
拋出ThreadAbortException
。
當您在頁面處理程序中使用此方法來終止對一個頁面的請求並啟動對另一頁面的新請求時,請將endResponse設置為false,然后調用CompleteRequest方法。 如果為endResponse參數指定true,則此方法將為原始請求調用End方法,該方法在完成時將引發ThreadAbortException異常。 此異常對Web應用程序性能有不利影響,這就是為什么建議為endResponse參數傳遞false的原因。
您將其捕獲在catch
塊中,然后重定向到Issue.aspx。
您可以為ThreadAbortException
添加特定的異常處理程序
catch (Exception ex)
{
HttpContext.Current.Response.Redirect("Issue.aspx", false);
}
catch (ThreadAbortException ex)
{
}
或在第二個參數( endResponse
)設置為false
調用Redirect
Response.Redirect("Home.aspx", false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.