ASP.Net/Development/web.config — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 11:51, 26 мая 2010

Содержание

Adding culture detection to the Web.config file

 
<configuration>
   <system.web>
    
   <globalization culture="auto" uiCulture="auto" />
    
   </system.web>
</configuration>



<anonymousIdentification> configuration section settings

<configuration>
  <system.web>
    <anonymousIdentification
                enabled="false"
                cookieName=".ASPXANONYMOUS
                cookieTimeout="100000"
                cookiePath="/"
                cookieRequireSSL="false"
                cookieSlidingExpiration = "true"
                cookieProtection = "Validation"
                cookieLess="UseCookies|UseUri|AutoDetect|UseDeviceProfile"
                domain="...."  />
  </system.web>
</configuration>



Application-Level Trace Logging?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <trace
        enabled="false"
        requestLimit="10"
        pageOutput="false"
        traceMode="SortByTime"
    localOnly="true"
    />
 </system.web>
</configuration>



ASP.NET Page Configuration

<configuration>
  <system.web>
    <pages buffer="true"
           enableSessionState="true"
           enableViewState="true"
           enableViewStateMac="false"
           autoEventWireup="true"
           smartNavigation="false"
           master="~/401kMasterPage.master"
           pageBaseType="System.Web.UI.Page"
           userControlBaseType="System.Web.UI.UserControl"
           compilationMode="Auto"
           validateRequest="true" >
        <imports>
           <add namespace="Control.MyLibrary"/>
        </imports>
        <registerTagPrefixes>
           <add tagPrefix="myControl" namespace="Control.MyLibrary.Controls"/>
        </registertagPrefixes>
    </pages>
  </system.web>
</configuration>



asterisk (*) represents all users and the question mark (?) represents anonymous users

<system.web>
    <authorization>
        <allow roles="Admin" />
        <deny users="?" />
    </authorization>
</system.web>



authentication section

<configuration>
   <system.web>
      <authentication>
            <authentication mode="Windows">
      </authentication>
   </system.web>
</configuration>



compilation debug="true"

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
</configuration>



ConfigurationManager.AppSettings

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Application Settings</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <h1>Application Settings</h1>
      Title:<asp:Label ID="lblTitle" runat="server" />
      <br />
      ISBN:<asp:Label ID="lblISBN" runat="server" />
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
       {
          string strTitle = ConfigurationManager.AppSettings["appTitle"];
          lblTitle.Text = strTitle;
          lblISBN.Text = ConfigurationManager.AppSettings["appISBN"];
       }
    }
}
File: Web.Config
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
  <appSettings>
    <add key="appISBN" value="0-596-00487-7"/>
    <add key="appTitle" value="Programming ASP.NET"/>
  </appSettings>
  <system.web>
    <compilation debug="true"/>
    </system.web>
</configuration>



Configuring ASP.NET Runtime Settings

<configuration>
  <system.web>
    <httpRuntime
      useFullyQualifiedRedirectUrl="false"
      enable="true"
      idealTime="10"
      executionTimeout="90"
      maxRequestLength="4096"
      requestLengthDiskThreshold="512"
      appRequestQueueLimit="5000"
      requestPriority="High"
      minFreeThreads="8"
      minLocalRequestFreeThreads="4"
      appRequestQueueLimit="100"
      enableKernalOutputCache="true"
    />
  </system.web>
</configuration>



Configuring Session State with a connection string

 
<configuration>
  <connectionStrings>
    <add name = "myString"
         connectionString = "data source=local;user id=User;password=password" />
  </connectionStrings>
  <system.web>
    <sessionState
      mode="SQLServer"
      sqlConnectionString="myString"
      cookieless="false"
      timeout="20"
    />
  </system.web>
</configuration>



Create custom section in Web.Config

<A href="http://www.nfex.ru/Code/ASPDownload/CustomSectionIn.zip">CustomSectionIn.zip( 2 k)</a>

1. <A href="/Code/ASP/Development/Setcultureinthewebconfig.htm">Set culture in the web.config</a> 2. <A href="/Code/ASP/Development/Definedatabaseconnectionstringinwebconfig.htm">Define database connection string in web.config</a> 3. <A href="/Code/ASP/Development/Thissectionsetstheglobalizationsettingsoftheapplication.htm">This section sets the globalization settings of the application</a> 4. <A href="/Code/ASP/Development/Getvariablesfromglobalasax.htm">Get variables from global.asax</a> <A href="/Code/ASP/Development/Getvariablesfromglobalasax.htm"></a> 5. <A href="/Code/ASP/Development/Removekeyfromwebconfig.htm">Remove key from web.config</a> 6. <A href="/Code/ASP/Development/webconfigdefaulterrorpage.htm">web.config: default error page</a> 7. <A href="/Code/ASP/Development/webconfigappSettings.htm">web.config: appSettings</a> 8. <A href="/Code/ASP/Development/Indicatetheerrorpageinwebconfig.htm">Indicate the error page in web.config</a> 9. <A href="/Code/ASP/Development/webconfigredirecttoaurlforastatuscode.htm">web.config: redirect to a url for a status code</a> 10. <A href="/Code/ASP/Development/webconfigcustomerrorwithdefaultredirectandmode.htm">web.config: custom error with default redirect and mode</a> 11. <A href="/Code/ASP/Development/webconfigconfigureapplicationspecificconfigurationsettings.htm">web.config: configure application-specific configuration settings</a> 12. <A href="/Code/ASP/Development/webconfigcustomErrors.htm">web.config: customErrors</a> 13. <A href="/Code/ASP/Development/webconfigsessionState.htm">web.config: session State</a> 14. <A href="/Code/ASP/Development/webconfigFormsauthentication.htm">web.config: Forms authentication</a> 15. <A href="/Code/ASP/Development/webconfigauthorization.htm">web.config: authorization</a> 16. <A href="/Code/ASP/Development/webconfigtracemode.htm">web.config: trace mode </a> 17. <A href="/Code/ASP/Development/webconfigauthenticationmode.htm">web.config: authentication mode</a> 18. <A href="/Code/ASP/Development/ApplicationLevelTraceLogging.htm">Application-Level Trace Logging?</a> 19. <A href="/Code/ASP/Development/DynamicDebugCompilation.htm">Dynamic Debug Compilation</a> 20. <A href="/Code/ASP/Development/CustomErrorMessages.htm">Custom Error Messages</a> 21. <A href="/Code/ASP/Development/AddingculturedetectiontotheWebconfigfile.htm">Adding culture detection to the Web.config file</a> 22. <A href="/Code/ASP/Development/SessionStateconfiguration.htm">Session State configuration</a> 23. <A href="/Code/ASP/Development/HTTPModuleconfiguration.htm">HTTP Module configuration</a> 24. <A href="/Code/ASP/Development/Storingaconnectionstring.htm">Storing a connection string</a> 25. <A href="/Code/ASP/Development/ConfiguringSessionStatewithaconnectionstring.htm">Configuring Session State with a connection string</a> 26. <A href="/Code/ASP/Development/specifycustomproviderassemblythatinheritstheSessionStateStoreProviderBaseclass.htm">specify custom provider assembly that inherits the SessionStateStoreProviderBase class</a> 27. <A href="/Code/ASP/Development/Thecompilationsection.htm">The compilation section</a> 28. <A href="/Code/ASP/Development/authenticationsection.htm">authentication section</a> 29. <A href="/Code/ASP/Development/FormsAuthentication.htm">Forms Authentication</a> 30. <A href="/Code/ASP/Development/anonymousIdentificationconfigurationsectionsettings.htm"><anonymousIdentification> configuration section settings</a> 31. <A href="/Code/ASP/Development/URLAuthorizationinthewebconfigfilewithallowanddenyattributes.htm">URL Authorization in the web.config file with <allow> and <deny> attributes</a> 32. <A href="/Code/ASP/Development/asteriskrepresentsallusersandthequestionmarkrepresentsanonymoususers.htm">asterisk (*) represents all users and the question mark (?) represents anonymous users</a> 33. <A href="/Code/ASP/Development/grantordenyaccesstotheusersorgroupsinregardtotheHTTPmethods.htm">grant or deny access to the users or groups in regard to the HTTP methods</a> 34. <A href="/Code/ASP/Development/FileAuthorization.htm">File Authorization</a> 35. <A href="/Code/ASP/Development/Setthesecurityforasinglefile.htm">Set the security for a single file</a> 36. <A href="/Code/ASP/Development/LockingDownConfigurationSettings.htm">Locking-Down Configuration Settings</a> 37. <A href="/Code/ASP/Development/ASPNETPageConfiguration.htm">ASP.NET Page Configuration</a> 38. <A href="/Code/ASP/Development/ConfiguringASPNETRuntimeSettings.htm">Configuring ASP.NET Runtime Settings</a> 39. <A href="/Code/ASP/Development/DefaultformatfortheprocessModelsection.htm">Default format for the <processModel> section</a> 40. <A href="/Code/ASP/Development/Customconfigurationsetting.htm">Custom configuration setting</a> 41. <A href="/Code/ASP/Development/SethttpRuntimemaxRequestLength2048.htm">Set httpRuntime maxRequestLength="2048"</a> 42. <A href="/Code/ASP/Development/compilationdebugtrue.htm">compilation debug="true"</a> 43. <A href="/Code/ASP/Development/ConfigurationManagerAppSettings.htm">ConfigurationManager.AppSettings</a> 44. <A href="/Code/ASP/Development/CustomConfigurationSections.htm">Custom Configuration Sections</a>

Custom Configuration Sections

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>Custom Configuration Sections</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <h1>Custom Configuration Sections</h1>
       <asp:Label ID="lblTime" runat="server" />
       <br />
       <asp:Label ID="lblTest" runat="server" />
       <br />
       <asp:Label ID="lblContent" runat="server" />
       <br />
       
       <asp:GridView ID="gv" runat="server" />
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
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.Collections;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
       lblTime.Text = "Posted at " + DateTime.Now.ToLongTimeString();
       if (!IsPostBack)
       {
          string strTest;
          strTest = ((Hashtable)ConfigurationManager.GetSection("altDB"))["Test"].ToString();
          lblTest.Text = strTest;
          lblContent.Text = ((Hashtable)ConfigurationManager.GetSection("altDB"))["Content"].ToString();
          CreateGrid();
       }
    }
   private void CreateGrid()
   {
      DataSet dsGrid = new DataSet();
      dsGrid = (DataSet)ConfigurationManager.GetSection("system.web/DataSetSectionHandler");
      gv.DataSource = dsGrid.Tables[0];
      gv.DataBind();
   }
}
File: SectionHandlers.cs
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
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 class DataSetSectionHandler : IConfigurationSectionHandler
{
   public Object Create(Object parent,Object configContext,System.Xml.XmlNode section)
   {
      string strSql;
      strSql = section.Attributes.Item(0).Value;
      string connectionString = "server=Local; uid=sa; pwd=password; database=Northwind";
      SqlDataAdapter da = new SqlDataAdapter(strSql,connectionString);
      DataSet dsData = new DataSet();
      da.Fill(dsData, "Customers");
      return dsData;
   }
}
File: Web.Config
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
  <configSections>
    <section name="altDB" type="System.Configuration.DictionarySectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <sectionGroup name="system.web">
      <section name="DataSetSectionHandler" type="DataSetSectionHandler,SectionHandlers" />
    </sectionGroup>
  </configSections>
  <altDB>
    <add key="Test" value=" SERVER=MyServer;DATABASE=Test;UID=myID;PWD=secret;" />
    <add key="Content" value=" SERVER=MyServer;DATABASE=Content;UID=myID;PWD=secret;" />
  </altDB>
  <appSettings/>
  <connectionStrings/>
  
  <system.web>
    <compilation debug="true"/>
    <authentication mode="Windows" />
    <DataSetSectionHandler  str="Select CompanyName,ContactName,City from Customers"  />
  </system.web>
</configuration>



Custom configuration setting

using System;
using MyNamespace;
namespace MyNamespace
{
    public class MySettings
    {
      public float Foo
      {
        get { return this.foo; }
        set { this.foo = value; }
      }
    
      float foo;
    
      public string Bar
      {
        get { return this.bar; }
        set { this.bar = value; }
      }
    
      string bar;
    
      const string SECTION_NAME = "MyStuff";
      static MySettings _settings = (MySettings)System.Configuration.ConfigurationManager.GetSection("MySettings");
        
      public static MySettings Settings
      {
        get
        {
          return _settings;
        }
      }
  }
}
File: Web.config
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="MySettings" type="Configuration.XmlSerializerSectionHandler, ConfigurationExamples"/>
    <section name="MySection" type="Configuration.MySection, ConfigurationExamples" />
  </configSections>
  <appSettings>
    <add key="MySetting" value="MyValue"/>
    <add key="AnotherSetting" value="AnotherValue"/>
  </appSettings>
  <MySettings type="MyNamespace.MySettings, ConfigurationExamples">
    <Foo>1.234</Foo>
    <Bar>A bunch of information</Bar>
  </MySettings>
</configuration>



Custom Error Messages

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
  <customErrors mode="RemoteOnly" defaultRedirect="/Maintenance.aspx" >
    <error statusCode="404" redirect="/NotFound.aspx" />
  </customErrors>
 </system.web>
</configuration>



Default format for the <processModel> section

<processModel 
   enable="true|false"
   timeout="hrs:mins:secs|Infinite"
   idleTimeout="hrs:mins:secs|Infinite"
   shutdownTimeout="hrs:mins:secs|Infinite"
   requestLimit="num|Infinite"
   requestQueueLimit="num|Infinite"
   restartQueueLimit="num|Infinite"
   memoryLimit="percent"
   cpuMask="num"
   webGarden="true|false"
   userName="username"
   password="password"
   logLevel="All|None|Errors"
   clientConnectedCheck="hrs:mins:secs|Infinite"
   responseDeadlockInterval="hrs:mins:secs|Infinite"
   responseRestartDeadlockInterval="hrs:mins:secs|Infinite"
   comAuthenticationLevel="Default|None|Connect|Call|
   Pkt|PktIntegrity|PktPrivacy"
   comImpersonationLevel="Default|Anonymous|Identify|
   Impersonate|Delegate"
   maxWorkerThreads="num"
   maxIoThreads="num"
/>



Define database connection string in web.config

<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.Data.SqlClient" %>
<html>
  <body>
    <h4>First Example: Listing data from the Employees table</h4>
    <asp:DataGrid id="dgNameList"
                  runat="server"
                  Gridlines="None"
                  BackColor="LightBlue"
                  CellPadding="5"
                  CellSpacing="5"
                  BorderWidth="2"
                  BorderColor="Black"
                  ToolTip="Includes only those employees who are at HQ" />
  <body>
</html>
<script language="VB" runat="server">
Sub Page_Load(Source As Object, E As EventArgs)
  Dim strConnection As String = ConfigurationSettings.AppSettings("yourSettingInWebConfig")
  Dim objConnection As New SqlConnection(strConnection)
  Dim strSQL As String = "SELECT FirstName, LastName, Country " & _
                         "FROM Employees;"
  Dim objCommand As New SqlCommand(strSQL, objConnection)
  objConnection.Open()
  Response.Write("ServerVersion: " & objConnection.ServerVersion & _
                 vbCRLF & "Datasource: " & objConnection.DataSource & _
                 vbCRLF & "Database: " & objConnection.Database)
  dgNameList.DataSource = objCommand.ExecuteReader()
  dgNameList.DataBind()
  objConnection.Close()
End Sub
</script>
<%--
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
     <customErrors mode="Off" />
     <compilation debug="true"/>
  </system.web>
  <appSettings>
    <add key="yourSettingInWebConfig"
         value="server=(local)\NetSDK; database=Northwind; integrated security=SSPI" />
  </appSettings>
</configuration>
--%>



Dynamic Debug Compilation

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation 
         defaultLanguage="c#"
         debug="true"
    />
 </system.web>
</configuration>



File Authorization

<location path="Documents">
    <system.web>
        <authorization>
            <allow roles="Admin" />
        </authorization>
    </system.web>
</location>



Forms Authentication

<configuration>
   <system.web>
      <authentication mode="Forms">
         <forms
            name="[name]"
            loginUrl="[url]"
            protection="[All|None|Encryption|Validation]"
            timeout="30"
            path="/"
            requireSSL="[true|false]"
            slidingExpiration="[true|false]"
            cookieless="UseCookies|UseUri|AutoDetect|UseDeviceProfile"
            defaultUrl="[url]"
            domain="string"
            >
            <credentials passwordFormat="[Clear, SHA1, MD5]">
              <user name="[UserName]" password="[password]"/>
            </credentials>
         </forms>
      </authentication>
   </system.web>
</configuration>



Get variables from global.asax

<%@ Page Language=VB Debug=true %>
<script runat=server>
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
    lblAppName.Text = Application("ApplicationName")
    lblAppName.ForeColor = System.Drawing.Color.FromName _
        (Application("FontColor"))
    lblMessage.ForeColor = System.Drawing.Color.FromName _
        (Application("FontColor"))
End Sub
Sub SubmitBtn_Click(Sender As Object, E As EventArgs)
    lblMessage.Text = FormatCurrency(txtOrderTotal.Text * _
        Application("ShippingCharge"))
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>Coding the Application_OnStart Event</TITLE>
</HEAD>
<form runat="server">
<asp:label 
    id="lblAppName"
    font-size="14"
    runat="server"
/>
<BR><BR>
<asp:label 
    id="lblMessage"
    runat="server"
    text="Enter your order total to 
        see the shipping charge"
/>
<BR><BR>
<asp:textbox 
    id="txtOrderTotal" 
    columns="25"
    maxlength="30"
    runat=server 
/>
<BR><BR>
<asp:button 
    id="butOK"
    text="  OK  "
    onclick="SubmitBtn_Click" 
    runat="server"
/>
</Form>
</BODY>
</HTML>
<%--
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.Data.OLEDB" %>
<SCRIPT LANGUAGE="VB" RUNAT="Server">
Sub Application_OnStart()
    Application("TaxRate") = 0.5125
    Application("appConn") = New OleDbConnection( _
        "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
        & "DATA SOURCE=" & Server.MapPath _
        ("EmployeeDatabase.mdb;"))
    Application("ApplicationName") = "My Site"
    Application("FontColor") = "Red"
    Application("ShippingCharge") = .03
End Sub
Sub Application_OnEnd()
"    Dim MyLog as New EventLog
 "   MyLog.Log = "Application"
  "  MyLog.Source = "My Test ASP.NET Application"
   " MyLog.WriteEntry("The application ended at " _
    "    & Now() & ".")
End Sub
Sub Session_OnStart()
    Application("SessionStarts") = Application("SessionStarts") + 1
    Session.TimeOut = 1
"    Session("TheEventLog") = New EventLog
 "   Session("TheEventLog").Log = "Application"
  "  Application.Lock
    Application("TotalUsers") = Application("TotalUsers") _
        + 1
    Application.Unlock
    "If Len(Session("WhenEntered")) = 0 Then
    "    Response.Redirect("welcome.aspx")
    "    Session("WhenEntered") = Now()
    "End If
End Sub
Sub Session_OnEnd()
    Dim MyLog as New EventLog
    MyLog.Log = "Application"
    MyLog.Source = "A session that started on " _
        & Session("WhenEntered") & " ended at " _
        & Now()
    Application("SessionStops") = _
        Application("SessionStops") + 1
        
End Sub
"Sub Application_Error(Sender as Object, e as EventArgs)
"    Response.Redirect("errorshappen.aspx")
"End Sub
</SCRIPT>
--%>


<A href="http://www.nfex.ru/Code/ASPDownload/EmployeeDatabase.zip">EmployeeDatabase.zip( 10 k)</a>


grant or deny access to the users or groups in regard to the HTTP methods

<system.web>
    <authorization>
        <deny verb="GET" roles="Admin" />
        <deny verb="POST" users="*" />
    </authorization>
</system.web>



HTTP Module configuration

 
<configSections>
<httpModules>
  <section name="System.Web.Caching.OutputCacheModule" />
  <section name="System.Web.SessionState.SessionStateModule" />
</httpModules>
</configSections>



Indicate the error page in web.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <system.web>
      <customErrors defaultRedirect="Error.aspx" mode="On" />
   </system.web>
</configuration>

<%--
<%@ Page Language="VB" %>
<html>
<head>
   <title>Error page</title>
</head>
<body>
<h1>Error page</h1>
Error originated on: <%=Request.QueryString("aspxerrorpath") %>
</body>
</html>
--%>



Locking-Down Configuration Settings

<configuration>
    <location path="Default Web Site/MyLibrary" allowOverride="true">
        <trace enabled="false"/>
    </location>
</configuration>



Remove key from web.config

       
<configuration>
   <appSettings>
      <remove key="machineConfigKey"/>
   </appSettings>
   <system.web>
      <pages enableSessionState="false" />
   </system.web>
</configuration>



Session State configuration

 
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<system.web>
    <sessionState
       mode="InProc"
       stateConnectionString="tcpip=127.0.0.1:42424"
       stateNetworkTimeout="10"
       sqlConnectionString="data source=127.0.0.1; user id=sa; password=myPassword"
       cookieless="false"
       timeout="20"
    />
    </system.web>
</configuration>



Set culture in the web.config

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
  <system.web>
    <anonymousIdentification enabled="true"/>
    <profile>
      <properties>
        <add 
          name="UserCulture"
          defaultValue="en-US" />
        <add 
          name="UserUICulture"
          defaultValue="en" />
      </properties>
    </profile>
  </system.web>
</configuration>



Set httpRuntime maxRequestLength="2048"

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="2048" />
    </system.web>
</configuration>



Set the security for a single file

<configuration>
    <location path="Documents/Default.aspx">
        <system.web>
            <authorization>
                <allow roles="Admin" />
            </authorization>
        </system.web>
    </location>
</configuration>



specify custom provider assembly that inherits the SessionStateStoreProviderBase class

<configuration>
   <system.web>
      <sessionState
          mode="Custom"
           CustomProvider="CustomStateProvider">
         <providers>
           <add name="CustomStateProvider"
           type="CustomStateProviderAssembly,CustomStateProviderNamespace.CustomStateProviderSateProvider"/>
         </providers>
      </sesisonState>
   </system.web>
</configuration>



Storing a connection string

 
<configuration>
  <connectionStrings>
    <add
        name = "my"
        connectionString = "server=local;database=myDB;
        uid=WebUser;pwd=password" />
  </connectionStrings>
</configuration>

Retrieving a connection string (VB)
Public Sub Page_Load (sender As Object, e As EventArgs) 
    ...
    Dim dbConnection as New _
        SqlConnection(ConfigurationSettings.ConnectionStrings("my"))
    ...
End Sub
   
Retrieving a connection string (C#)
public void Page_Load (Object sender, EventArgs e) 
{
    ...
    SqlConnection dbConnection = new    
        SqlConnection(ConfigurationSettings.ConnectionStrings["my"]);
    ...
}



The compilation section

 
<!-- compilation Attributes -->
<compilation
  tempDirectory="directory"
  debug="[true|false]"
  strict="[true|false]"
  explicit="[true|false]"
  batch="[true|false]"
  batchTimeout="timeout in seconds"
  maxBatchSize="max number of pages per batched compilation"
  maxBatchGeneratedFileSize="max combined size in KB"
  numRecompilesBeforeAppRestart="max number of recompilations "
  defaultLanguage="name of a language as specified in a <compiler/> element below" 
   <compilers>
    <compiler language="language"
        extension="ext"
        type=".NET Type"
        warningLevel="number"  
        compilerOptions="options"/>
   </compilers>
   <assemblies>
    <add assembly="assembly"/>
   </assemblies> 
   <codeSubDirectories> 
   <codeSubDirectory directoryName="sub-directory name"/>
   </codeSubDirectories>
   <buildproviders> 
   <buildprovider
     extension="file extension"
     type="type reference"/>
   </buildproviders>
</compilation>



This section sets the globalization settings of the application

<?xml version="1.0"?>
<configuration>
  <system.web>
    <!--  GLOBALIZATION
           This section sets the globalization settings of the application. 
        -->
    <globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
  </system.web>
</configuration>



URL Authorization in the web.config file with <allow> and <deny> attributes

<system.web>
    <authorization>
        <allow users="Ssivakumar" />
        <deny roles="Sales, Marketing" />
    </authorization>
</system.web>



web.config: appSettings

<%@ Page Language="vb" %>
<html>
   <head>
      <script runat="server">
  Sub Page_Load()
     Dim i As Integer
           Dim nv As NameValueCollection
           nv = HttpContext.GetAppConfig("appSettings")
           For i = 0 To nv.Count - 1
              Response.Write(nv.GetKey(i) & " = " & nv(i) & "<br/>")
           Next
  End Sub
      </script>
   </head>
<body>
   <asp:label id="Message" runat="server"/>
</body>
</html>

<%--
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <appSettings>
      <add key="foo" value="bar"/>
      <add key="foo2" value="bar2"/>
   </appSettings>
</configuration>
--%>



web.config: authentication mode

<configuration> 
  <system.web>
    <authentication mode="Windows" />
  </system.web>
</configuration>



web.config: authorization

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.web>

        <!--
            The <authorization> section enables developers/administrators to configure 
            whether a user or role has access to a particular page or resource.  This is 
            accomplished by adding "<allow>" and "<deny>" sub-tags beneath the <authorization> 
            section - specifically detailing the users/roles allowed or denied access.
            Note: The "?" character indicates "anonymous" users (ie: non authenticated users).  
            The "*" character indicates "all" users. 
        -->
            <authorization>
               <allow users="joeuser" />
               <allow roles="Admins" />
               <deny users="*" />
            </authorization>

    </system.web>
</configuration>



web.config: configure application-specific configuration settings

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!-- 
    The <appSettings> section is used to configure application-specific configuration 
    settings.  These can be fetched from within apps by calling the 
    "ConfigurationSettings.AppSettings(key)" method:
-->
     <appSettings>
        <add key="connectionstring" value="server=localhost;trusted_connection=true;database=pubs"/>
     </appSettings>
</configuration>



web.config: customErrors

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.web>
<!--
  The <customErrors> section enables configuration of what to do if/when an 
  unhandled error occurs during the execution of a request.  Specifically, it 
  enables developers to configure html error pages to be displayed in place of 
  a error stack trace:
-->    
       <customErrors mode="On">
          <error statusCode="404" redirect="FileNotFound.aspx"/>
       </customErrors>
    </system.web>
</configuration>



web.config: custom error with default redirect and mode

<configuration>
 <system.web> 
   <customErrors defaultRedirect="userError.aspx" mode="RemoteOnly">
  <error statusCode="404" redirect="pagenotfound.aspx" />
 </customErrors>
 </system.web>
</configuration>



web.config: default error page

<configuration>
   <system.web>
      <customErrors mode="Off" defaultRedirect="GetLastError.aspx" />
   </system.web>
</configuration>



web.config: Forms authentication

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.web>
        <!-- 
            The <authentication> section enables configuration of the security authentication 
            mode used by ASP.NET to identify an incoming user.  It supports a "mode" 
            attribute with four valid values: "Windows", "Forms", "Passport" and "None":  
            The <forms> section is a sub-section of the <authentication> section, 
            and supports configuring the authentication values used when Forms 
            authentication is enabled above:
        -->
            <authentication mode="Windows">
                    <forms name=".ASPXAUTH" 
                           loginUrl="login.aspx" 
                           protection="Validation" 
                           timeout="999999" />
             </authentication>

    </system.web>
</configuration>



web.config: redirect to a url for a status code

<configuration>
 <system.web> 
   <customErrors defaultRedirect="userError.aspx" mode="RemoteOnly">
  <error statusCode="404" redirect="pagenotfound.aspx" />
 </customErrors>
 </system.web>
</configuration>



web.config: session State

<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <system.web>
        <!-- 
            The <sessionState" section is used to configure session state for the application.  
            It supports four modes: "Off", "InProc", "StateServer", and "SqlServer".  The 
            later two modes enable session state to be stored off the web server machine - 
            allowing failure redundancy and web farm session state scenarios.
        -->
        <sessionState mode="InProc"
                      stateConnectionString="tcpip=127.0.0.1:42424"
                      sqlConnectionString="data source=127.0.0.1;trusted_connection=true"
                      cookieless="false" 
                      timeout="20" />
    </system.web>
</configuration>



web.config: trace mode

<configuration>
  <system.web>
    <trace 
      enabled="true" 
      requestLimit = "10"
      pageOutput="false"
      traceMode="SortByTime"
      localOnly = "true"
    />
  </system.web>
</configuration>