Currently, I have some code as follows:
目前,我有一些代码如下:
protected override void OnLoad(EventArgs e)
{
if(IsAuthorized(param1, param2, ...))
{
//snip
}
else
{
Response.Write("Not authorized");
}
}
protected void MyButton1_Click(object sender, EventArgs e)
{
//snip
}
protected void MyButton2_Click(object sender, EventArgs e)
{
//snip
}
When the user is logged in, they can go to the page and OnLoad runs. Now, if they let their session expire with the page still open, then try to click MyButton1, they will be greeted with "Not authorized", but the code inside MyButton1_Click will still run. Could anyone point me in the direction of how I would correctly handle this type of situation? I assumed I could just throw new SecurityException(), then display whatever error I wanted in the catch(SecurityException), however the event handler still runs. Thanks in advance.
当用户登录时,他们可以转到该页面并运行OnLoad。现在,如果他们的会话在页面仍然打开的情况下过期,然后尝试单击MyButton1,他们将会收到“未授权”,但MyButton1_Click中的代码仍会运行。有人能指出我如何正确处理这种情况的方向吗?我假设我可以抛出新的SecurityException(),然后在catch(SecurityException)中显示我想要的任何错误,但事件处理程序仍然运行。提前致谢。
1 个解决方案
#1
You can throw an authentication check around your code such as this code from MSDN:
您可以对代码进行身份验证检查,例如来自MSDN的此代码:
private void Page_Load(object sender, EventArgs e)
{
// Check whether the current request has been
// authenticated. If it has not, redirect the
// user to the Login.aspx page.
if (!Request.IsAuthenticated)
{
Response.Redirect("Login.aspx", true);
}
}
I believe this is cleaner than the Response.Write()
since the user clearly sees that they're no longer authenticated.
我相信这比Response.Write()更干净,因为用户清楚地看到它们不再经过身份验证。
#1
You can throw an authentication check around your code such as this code from MSDN:
您可以对代码进行身份验证检查,例如来自MSDN的此代码:
private void Page_Load(object sender, EventArgs e)
{
// Check whether the current request has been
// authenticated. If it has not, redirect the
// user to the Login.aspx page.
if (!Request.IsAuthenticated)
{
Response.Redirect("Login.aspx", true);
}
}
I believe this is cleaner than the Response.Write()
since the user clearly sees that they're no longer authenticated.
我相信这比Response.Write()更干净,因为用户清楚地看到它们不再经过身份验证。