代码如下
using System;
using System.Web.Configuration;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class EncDecWebConfig : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// load web.config into TextBox on first page visit...
if (!Page.IsPostBack)
{
RefreshWebConfig();
}
}
private void RefreshWebConfig()
{
// Read in the value of Web.config into the TextBox...
using (StreamReader reader = File.OpenText(Server.MapPath("~/Web.config")))
{
webConfig.Text = reader.ReadToEnd();
}
// Programmatically read in the value of the connection string
PlainTextConnectionString.Text = ConfigurationManager.ConnectionStrings["MembershipConnectionString"].ConnectionString;
}
#region "Protect/Unprotect Methods"
// Code taken verbatim from David Hayden's blog [http://davidhayden.com/blog/dave/]
// Entry: Encrypt Connection Strings AppSettings and Web.Config in ASP.NET 2.0 - Security Best Practices
// [http://davidhayden.com/blog/dave/archive/2005/11/17/2572.aspx]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>Encrypting Configuration Information Demo</h1>
<p>Note how the plain-text value of the MembershipConnectionString is available
programmatically using the exact same code, regardless of whether the <code><connectionStrings></code>
section is encrypted or not...</p>
<b>Value of the MembershipConnectionString:</b>
<asp:Label ID="PlainTextConnectionString" runat="server"></asp:Label><br /><br />
<b>Contents of Web.config:</b>
<asp:TextBox ID="webConfig" TextMode="MultiLine" Width="97%" Rows="20" runat="server"></asp:TextBox>
<p>
<asp:Button ID="btnRefreshWebConfig" runat="server" Text="Refresh" OnClick="btnRefreshWebConfig_Click" />