ASP.NET Tutorial/Configuration/WebConfigurationManager

Материал из .Net Framework эксперт
Версия от 11:57, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Get and set application settings

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Welcome_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
          
        <asp:Label id="lblSiteName" runat="server" Font-Bold="True" Font-Size="Large"></asp:Label>
      
        <asp:Label id="lblWelcome" runat="server" Font-Names="Tahoma"></asp:Label>
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
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;
using System.Web.Configuration;
public partial class Welcome_aspx : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    
    lblSiteName.Text = config.AppSettings.Settings["websiteName"].Value;
    lblWelcome.Text = config.AppSettings.Settings["welcomeMessage"].Value;
    if (config.AppSettings.Settings["welcomeMessage"].Value.Length > 15)
    {
      config.AppSettings.Settings["welcomeMessage"].Value = "Welcome, again.";
    }
    else
    {
      config.AppSettings.Settings["welcomeMessage"].Value = "Welcome, friend.";
    }
    config.Save();
    
  }
}
File: Web.config
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
  <system.web>
  <appSettings>
    <add key="websiteName" value="My New Website" />
    <add key="welcomeMessage" value="Welcome, again." />
  </appSettings>

</configuration>


Opening a Configuration File

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        Configuration config = WebConfigurationManager.OpenMachineConfiguration();        
        AuthenticationSection section = (AuthenticationSection)config.GetSection ("system.web/authentication");
        lblMode.Text = section.Mode.ToString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Config Machine</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Authentication Mode Default Value:
    <asp:Label
        id="lblMode"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Read configuration

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ReadWriteConfiguration_aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
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;
using System.Web.Configuration;
public partial class ReadWriteConfiguration_aspx : System.Web.UI.Page
{   
    protected void Page_Load(object sender, EventArgs e)
    {
    foreach (ConnectionStringSettings connection in
      WebConfigurationManager.ConnectionStrings)
    {
      Response.Write("Name: " + connection.Name + "<br />");
      Response.Write("Connection String: " +
        connection.ConnectionString + "<br /><br />");
    }
    Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
    CompilationSection compSection = (CompilationSection)config.GetSection(@"system.web/compilation");
    foreach (AssemblyInfo assm in compSection.Assemblies)
    {
      Response.Write(assm.Assembly + "<br /");
    }    
    }
}

File: Web.config
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
  <system.web>

    <compilation debug="true">
      <assemblies>
        <add assembly="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <authentication mode="Windows"/>
  </system.web>

</configuration>


Retrieving a configuration setting with the GetSection() and GetWebApplicationSection() methods.

File: SubFolder\ShowConfigRelative.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {        CompilationSection section = (CompilationSection)WebConfigurationManager.GetSection("system.web/compilation");
        lblDebug1.Text = section.Debug.ToString();
        section = (CompilationSection)WebConfigurationManager.GetWebApplicationSection("system.web/compilation");
        lblDebug2.Text = section.Debug.ToString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Config Relative</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    GetSection Debug:
    <asp:Label
        id="lblDebug1"
        Runat="server" />
    <br /><br />
    GetWebApplicationSection Debug:
    <asp:Label
        id="lblDebug2"
        Runat="server" />
    </div>
    </form>
</body>
</html>


Update Configuration

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="UpdateConfig" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Update Configuration</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
            <asp:Button ID="Button1" runat="server" Text="Stop access to .XYZ Resources" OnClick="Button1_Click" />&nbsp;
            <br />
            <asp:Button ID="Button2" runat="server" Text="Re-enable access to .XYZ Resources" OnClick="Button2_Click" />&nbsp;
            <br />
            <asp:Button ID="Button3" runat="server" Text="Encrypt connectionStrings" OnClick="Button3_Click" />&nbsp;
            <br />
            <asp:Button ID="Button5" runat="server" Text="Read Connection String" OnClick="Button5_Click" />&nbsp;
            <br />
            <asp:Button ID="Button4" runat="server" Text="Decrypt connectionStrings" OnClick="Button4_Click" />&nbsp;
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;

public partial class UpdateConfig : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        string name = @"system.web/httpHandlers";
        string path = "/";
        Configuration appConfig = WebConfigurationManager.OpenWebConfiguration(path);
        HttpHandlersSection section = (HttpHandlersSection)appConfig.GetSection(name);

        HttpHandlerAction newHandler = new HttpHandlerAction(
            "*.xyz", "System.Web.HttpForbiddenHandler", "*");
        section.Handlers.Add(newHandler);
        appConfig.Save();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string name = @"system.web/httpHandlers";
        string path = "/";
        Configuration appConfig = WebConfigurationManager.OpenWebConfiguration(path);
        HttpHandlersSection section = (HttpHandlersSection)appConfig.GetSection(name);
        section.Handlers.Remove("*", "*.xyz");
        appConfig.Save();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        string name = "connectionStrings";
        string path = "/";
        Configuration cfg = WebConfigurationManager.OpenWebConfiguration(path);
        ConnectionStringsSection section;
        section = (ConnectionStringsSection) cfg.GetSection(name);
        section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
        cfg.Save();
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        string name = "connectionStrings";
        string path = "/";
        Configuration cfg = WebConfigurationManager.OpenWebConfiguration(path);
        ConnectionStringsSection section;
        section = (ConnectionStringsSection)cfg.GetSection(name);
        section.SectionInformation.UnprotectSection();
        cfg.Save();
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        Response.Write(WebConfigurationManager.ConnectionStrings["LocalNWind"].ConnectionString);
    }
}


Using the Configuration API

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    void Page_Load()
    {
        CompilationSection section = (CompilationSection)WebConfigurationManager.GetWebApplicationSection("system.web/compilation");
        lblDebug.Text = section.Debug.ToString();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Config App</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Debug Mode:
    <asp:Label
        id="lblDebug"
        Runat="server" />
    </div>
    </form>
</body>
</html>