I think the direct answer to your question is it can't be done server-side once the initial page is loaded - that is, response is sent to the client, and server-side code is out of the picture, until the next request. Such is the nature of the web.
My recommendation is to move this functionality client-side. You'll need an XmlHttpRequest
(XHR, aka AJAX) call to the server (think API call, just to your own server) to determine whether or not a redirect is necessary based on your specific rules/logic. The response to such XHR call can be as simple as a boolean, or can include the URL of the redirect.
If you want to take advantage of built-in WebForms facilities to handle a client-side redirection, you can use Web.UI.Timer
instead, along with a ScriptManager
control:
In ASPX code:
<asp:ScriptManager ID="scriptManager" runat="server"></asp:ScriptManager>
<asp:Timer runat="server" ID="redirectTimer" Interval="5000" OnTick="redirectTimer_Tick" Enabled="true" />
In code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Handle initial page load
}
}
protected void redirectTimer_Tick(object sender, EventArgs e)
{
if(someConditionIsSatisfied)
{
Response.Redirect(myUri, false);
}
}
Keep in mind, the Timer.Tick
event in the above code will cause a full post-back - that is, your page will fully re-load. You can use other mechanisms, such as an update panel, to "hide" the reload from the client, but any code in your Page_Load()
event handler will run on every timer tick; just be aware of that.
You can ensure your Page_Load()
code executes only once by checking the Page.IsPostBack
property.
Bottom line, you're trying to accomplish your task in the wrong context - this is a job for the client, not the server, to handle.