您应该使用 cookie 和用户控件模拟 asp.net 路由。
所以我们只有一个名为 default.aspx 的 aspx 文件,其他页面应该放在用户控件中。
将此脚本放在 default.aspx 的末尾:
<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("a").click(function (e) {
e.preventDefault();
var attrHref = $(this).attr("href");
$.getJSON("/service.asmx/SetRouteCookie", { href: attrHref }, function (e) {
window.location.reload();
});
});
});
</script>
此脚本禁用所有链接行为,然后我们手动处理点击事件。
在单击事件中,我们通过 ajax 调用 Web 服务方法。该服务设置了某个 cookie 来保存当前页面:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false, UseHttpGet = true)]
public void SetRouteCookie()
{
if (HttpContext.Current.Request.QueryString["href"] != null)
{
string href = HttpContext.Current.Request.QueryString["href"];
HttpCookie c = new HttpCookie("CurrentRoute", href);
c.Expires = DateTime.Now.AddHours(1);
HttpContext.Current.Response.Cookies.Add(c);
HttpContext.Current.Response.ContentType = "application/json";
HttpContext.Current.Response.Write("{\"status\":\"ok\"}");
}
}
在创建 cookie 并成功回调后,我们通过 javascript 重新加载页面。
在默认的 Page_Load 事件中,我们加载适当的用户控件:
protected void Page_Load(object sender, EventArgs e)
{
#region process route
if (HttpContext.Current.Request.Cookies["CurrentRoute"] != null)
{
var route = HttpContext.Current.Request.Cookies["CurrentRoute"].Value.ToString();
string pageName = GetPageName(route);
Placeholder1.Controls.Add(LoadControl("/ctrls/" + pageName + ".ascx"));
}
else
{
Placeholder1.Controls.Add(LoadControl("/ctrls/default.ascx"));
}
#endregion
}
public string GetPageName(string href)
{
int index = href.IndexOf("&");
if (index == -1)
return href.Trim('/');
else
{
return href.Substring(0, index).Trim('/');
}
}
我在 git 上创建了示例代码:
HideRoute