常見場景:Session 過期導向登入頁,登入成功後自動跳回原操作頁。`Request.UrlReferrer` 即可輕鬆實現。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// 1. 保存來源頁面
if (Request.UrlReferrer != null)
ViewState["ReturnUrl"] = Request.UrlReferrer.ToString();
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
// ... 驗證邏輯 ...
if (success)
{
string returnUrl = ViewState["ReturnUrl"] as string;
if (!string.IsNullOrEmpty(returnUrl))
Response.Redirect(returnUrl);
else
Response.Redirect("Default.aspx");
}
}
public class AuthHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += (s, e) =>
{
var app = (HttpApplication)s;
if (app.Request.UrlReferrer != null &&
!app.Request.Url.AbsolutePath.Contains("Login") &&
app.Session["User"] == null)
{
// 保存原始請求 URL 含 QueryString
app.Session["ReturnUrl"] = app.Request.RawUrl;
app.Response.Redirect("~/Login.aspx");
}
};
}
}
在 `web.config` 註冊模組,全站自動攔截未登入請求並保存返回地址。