ASP.Net/Development/web.config

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

Содержание

Adding culture detection to the Web.config file

   <source lang="csharp">

<configuration>

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

</configuration>

</source>
   
  


<anonymousIdentification> configuration section settings

   <source lang="csharp">

<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>

</source>
   
  


Application-Level Trace Logging?

   <source lang="csharp">


<?xml version="1.0" encoding="utf-8" ?> <configuration>

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

</configuration>

</source>
   
  


ASP.NET Page Configuration

   <source lang="csharp">

<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>

</source>
   
  


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

   <source lang="csharp">

<system.web>

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

</system.web>

</source>
   
  


authentication section

   <source lang="csharp">

<configuration>

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

</configuration>

</source>
   
  


compilation debug="true"

   <source lang="csharp">

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

 <system.web>
   <compilation debug="true" />
 </system.web>

</configuration>

</source>
   
  


ConfigurationManager.AppSettings

   <source lang="csharp">

<%@ 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">

Application Settings

     Title:<asp:Label ID="lblTitle" runat="server" />
     
ISBN:<asp:Label ID="lblISBN" runat="server" />
   </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>

</source>
   
  


Configuring ASP.NET Runtime Settings

   <source lang="csharp">

<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>

</source>
   
  


Configuring Session State with a connection string

   <source lang="csharp">

<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>

</source>
   
  


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

   <source lang="csharp">

<%@ 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">

Custom Configuration Sections

      <asp:Label ID="lblTime" runat="server" />
      
<asp:Label ID="lblTest" runat="server" />
<asp:Label ID="lblContent" runat="server" />
<asp:GridView ID="gv" runat="server" />
   </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>

</source>
   
  


Custom configuration setting

   <source lang="csharp">

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>

</source>
   
  


Custom Error Messages

   <source lang="csharp">

<?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>

</source>
   
  


Default format for the <processModel> section

   <source lang="csharp">

<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"

/>

</source>
   
  


Define database connection string in web.config

   <source lang="csharp">

<%@ Import namespace="System.Data" %> <%@ Import namespace="System.Data.SqlClient" %> <html>

 <body>

First Example: Listing data from the Employees table

   <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> --%>

      </source>
   
  


Dynamic Debug Compilation

   <source lang="csharp">

<?xml version="1.0" encoding="utf-8" ?> <configuration>

 <system.web>
   <compilation 
        defaultLanguage="c#"
        debug="true"
   />
</system.web>

</configuration>

</source>
   
  


File Authorization

   <source lang="csharp">

<location path="Documents">

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

</location>

</source>
   
  


Forms Authentication

   <source lang="csharp">

<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>

</source>
   
  


Get variables from global.asax

   <source lang="csharp">

<%@ 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"

/>

<asp:label

   id="lblMessage"
   runat="server"
   text="Enter your order total to 
       see the shipping charge"

/>

<asp:textbox

   id="txtOrderTotal" 
   columns="25"
   maxlength="30"
   runat=server 

/>

<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> --%>

      </source>
   
  

<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

   <source lang="csharp">

<system.web>

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

</system.web>

</source>
   
  


HTTP Module configuration

   <source lang="csharp">

<configSections> <httpModules>

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

</httpModules> </configSections>

</source>
   
  


Indicate the error page in web.config

   <source lang="csharp">

<?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>

Error page

Error originated on: <%=Request.QueryString("aspxerrorpath") %> </body> </html> --%>

      </source>
   
  


Locking-Down Configuration Settings

   <source lang="csharp">

<configuration>

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

</configuration>

</source>
   
  


Remove key from web.config

   <source lang="csharp">
      

<configuration>

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

</configuration>


      </source>
   
  


Session State configuration

   <source lang="csharp">

<?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>

</source>
   
  


Set culture in the web.config

   <source lang="csharp">

<?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>

      </source>
   
  


Set httpRuntime maxRequestLength="2048"

   <source lang="csharp">

<configuration>

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

</configuration>

</source>
   
  


Set the security for a single file

   <source lang="csharp">

<configuration>

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

</configuration>

</source>
   
  


specify custom provider assembly that inherits the SessionStateStoreProviderBase class

   <source lang="csharp">

<configuration>

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

</configuration>

</source>
   
  


Storing a connection string

   <source lang="csharp">

<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"]);
   ...

}

</source>
   
  


The compilation section

   <source lang="csharp">

<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>

</source>
   
  


This section sets the globalization settings of the application

   <source lang="csharp">

<?xml version="1.0"?> <configuration>

 <system.web>
   
   <globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
 </system.web>

</configuration>

      </source>
   
  


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

   <source lang="csharp">

<system.web>

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

</system.web>

</source>
   
  


web.config: appSettings

   <source lang="csharp">

<%@ 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) & "
") 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> --%>

      </source>
   
  


web.config: authentication mode

   <source lang="csharp">

<configuration>

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

</configuration>

      </source>
   
  


web.config: authorization

   <source lang="csharp">

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

   <system.web>


           <authorization>
              <allow users="joeuser" />
              <allow roles="Admins" />
              <deny users="*" />
           </authorization>
   </system.web>

</configuration>

      </source>
   
  


web.config: configure application-specific configuration settings

   <source lang="csharp">

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

    <appSettings>
       <add key="connectionstring" value="server=localhost;trusted_connection=true;database=pubs"/>
    </appSettings>

</configuration>

      </source>
   
  


web.config: customErrors

   <source lang="csharp">

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

   <system.web>
   
      <customErrors mode="On">
         <error statusCode="404" redirect="FileNotFound.aspx"/>
      </customErrors>
   </system.web>

</configuration>

      </source>
   
  


web.config: custom error with default redirect and mode

   <source lang="csharp">

<configuration>

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

</configuration>

      </source>
   
  


web.config: default error page

   <source lang="csharp">

<configuration>

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

</configuration>

      </source>
   
  


web.config: Forms authentication

   <source lang="csharp">

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

   <system.web>
       
           <authentication mode="Windows">
                   <forms name=".ASPXAUTH" 
                          loginUrl="login.aspx" 
                          protection="Validation" 
                          timeout="999999" />
            </authentication>
   </system.web>

</configuration>

      </source>
   
  


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

   <source lang="csharp">

<configuration>

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

</configuration>

      </source>
   
  


web.config: session State

   <source lang="csharp">

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

   <system.web>
       
       <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>

      </source>
   
  


web.config: trace mode

   <source lang="csharp">

<configuration>

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

</configuration>

      </source>