Safely restart an ASP.NET remotely
-
2/12/2008
- Author:
Brian Pautsch
- Category:
Code Snippets
-
1545
Views
-
1
Comments
-
Every once in awhile, an ASP.NET website may need to be restarted. There are a few ways to do this: kill the worker process (too forceful), restart IIS (restarts all websites) or modify the web.config (best choice). Instead of FTP'ing the web.config down and back up or logging onto the server to update the web.config, why not create a web page that allows you to easily update the "last write date" on the file. The .NET Framework monitors website files and when the web.config write date changes, it automatically restarts that website. Here's code you can drop into an ASP.NET web page to accomplish this:
1<%@ Page Language="C#" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4
5<script runat="server">
6 protected void Page_Load(object sender, EventArgs e)
7 {
8 lblMessage.Text = "";
9 }
10
11 protected void btnRestart_Click(object sender, EventArgs e)
12 {
13 if (txtPassword.Text.Trim().ToUpper() ==
14 System.Configuration.ConfigurationManager.AppSettings["ResetSitePassword"].ToString().Trim().ToUpper())
15 {
16 string webConfigPath = Server.MapPath("~/Web.config");
17 System.IO.File.SetLastWriteTime(webConfigPath, DateTime.Now);
18 Session.Abandon();
19 Response.Redirect("/");
20 }
21 else
22 lblMessage.Text = "Invalid password";
23 }
24</script>
25
26<html xmlns="http://www.w3.org/1999/xhtml">
27<head runat="server">
28 <title>Restart Website</title>
29</head>
30<body>
31 <form id="aspnetForm" runat="server">
32 Password:
33 <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>
34 <asp:Button ID="btnRestart" runat="server" Text="Restart" OnClick="btnRestart_Click">
35 </asp:Button>
36 <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
37 </form>
38</body>
39</html>
User Comments
On
12/26/2008
Andy
said:
Nice trick. Thanks!
Leave a Comment