From time to time I have pages that need to auto-refresh or more commonly a page that automatically needs to go to another page after showing a short informational message. In the past I’ve always done this with Meta-Refresh tags in the page which looks like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Welcome Back</title>
<meta http-equiv="Refresh" content="2; URL=/wwstore/Profile" />
...
</head>
You can also do this in code in an ASP.NET WebForms page by adding an HtmlMeta()
control to the Page.Header.Controls
collection like this:
// Classic ASP.NET - WebForms
// *** Create META tag and add to header controls
HtmlMeta RedirectMetaTag = new HtmlMeta();
RedirectMetaTag.HttpEquiv = "Refresh";
RedirectMetaTag.Content = string.Format("{0}; URL={1}", this.Context.Items["ErrorMessage_Timeout"], NewUrl);
this.Header.Controls.Add(RedirectMetaTag);
But I never put 2 and 2 together to realize that the meta tag is actually mapping an actual HTTP Header. Meta tags are essentially page level overrides to actual Http headers, so meta-refresh
refers to the Refresh
Http header.
So, from a server generated application, it's actually much easier to add a refresh by adding the following to the Response headers like this:
Response.AppendHeader("Refresh", "4");
This refreshes the current page after 4 seconds by reloading itself.
Alternately to go to a different page:
Response.AppendHeader("Refresh", "4; url=/profile");
This is of course much shorter and cleaner. One advantage of the Meta tag approach is that if somebody bookmarks the page the Meta-Refresh will still fire even on a page that is browser cached, while the HTTP header most likely wouldn’t.
Where can you do this?
Adding Http headers via Response.AppendHeader()
can be done inside of the ASP.NET request processing. Since ASP.NET always caches responses you can delay adding the header until the very end of a request which allows you to conditionally set it based on Page logic.
Response.AppendHeader()
is also available in HttpHandlers
and HttpModuless
where the same up until the end rules apply.
Note: ASP.NET Core and other Web platforms do not cache headers and require that headers are written before any other content is sent to the Response
.
Ah, the little things that one can easily overlook that sometimes make things easier...
Other Posts you might also like