Web. config is a very important file in the ASP. I remember when I was a graduate in college, the question of a teacher in a defense was what does Web. config do? The answer is that the database connection can be stored inside the information, the teacher asked, what else can be done? I... Speechless.
Recently finishing the knowledge point, ready to lay a solid foundation, technology regardless of simplified, in order to step by step, to achieve real understanding and mastery. So specifically on the Internet to collect some information, some of the knowledge points are hit code verification once, recorded for the time to review.
- Web. config read and access mechanism
. NET program accesses a node in the configuration file, first try to find the appropriate node in Web. config in the current directory, such as if the file or node does not exist, follow the parent directory until the root directory is searched. If you have not found the corresponding node in the root directory, look in the%windir%\microsoft.net\framework\vx.0\config\web.config file. If it is still not found, look in the%windir%\microsoft.net\framework\vx.0\config\machine.config file. Returns null if it is still not found.
Asp. NET Web site IIS loads configuration information from the configuration file and caches it when it starts, so that you do not have to reread the configuration information every time. During the run, the application monitors the configuration file changes, and once the configuration information is modified, it is re-read and cached.
- Detailed description of each configuration section
Apply VS2013 to create a new Web application project, open the. config to see the basic structure such as:
1. configsections
The main function of configsections is to configure custom nodes, such as file upload Application, factory method application and so on.
code example:
1<configSections>2<sectiongroup name="Section Group name">3<section name="Section name"Type="configuration section Handler class"/>4</sectionGroup>5</configSections>6 7<section Group Name>8<section name>9<add key="Key1"Value="value1"/>Ten</section name> One</section Group Name>
View Code
After defining a node, you can return an object by implementing the IConfigurationSectionHandler interface, and then call System.Configuration.ConfigurationManager.GetSection () method to return the information of the node, the specific implementation of the online example, confined to the length of the issue, in the subsequent blog added.
2. ConnectionStrings
The main function of connectionstrings is to save the database connection string information.
code example:
1 <connectionStrings>2 <add name="defaultconnection" connectionstring="Data source=192.168.1.1;initial catalog=testdb; User Id=sa; Password=sa "providername="System.Data.SqlClient "/>3 </connectionStrings>
View Code
Get the connection string in the code:
1 configurationmanager.connectionstrings["defaultconnection"]. ConnectionString;
View Code
3. Compilation
code example:
1 <compilation debug="true" targetframework="4.5" defaultlanguage="C #" batch="true" />
View Code
debug = "true" means that debugging is enabled, inserting debug symbols into a compiled page can affect performance, so it should be enabled only in the development environment.
DefaultLanguage = "C #" setting the default language
Batch = "true" if batch processing is supported
4. Authentication
code example:
1 <authentication mode="None" />
View Code
There are three ways to verify how to set up asp:
(1) Windows
Authentication is provided directly through IIS.
(2) Forms
Validating with application-specific logic
(3) Passport
Validated by the centralized authentication service provided by Microsoft
Asp. NET authentication is a relatively complex point of knowledge, followed by a separate blog post to summarize.
5. AppSettings
AppSettings is typically used to store some common configuration information in a project.
Example code:
1 <appSettings>2 <add key="IP" value="192.168.0.1 "/>3 </appSettings>
View Code
The node location is located under the configuration root directory.
Example code that is called in the program:
1 configurationmanager.appsettings["IP"]. ToString ();
View Code
6. CustomErrors
For handling custom error messages, located under the <System.Web> configuration section.
The sample code is as follows:
1 <customerrors mode="RemoteOnly" defaultredirect= " error.html"></customErrors>
View Code
mode = "On" Local Users and remote users will see the custom error message.
mode = "Off" Disables custom error messages, and both local and remote users will see detailed error messages.
mode = "RemoteOnly" The local user will see the detailed error message, and the remote user will see the custom error message.
defaultredirect = "error.html" The URL of the redirect when an error occurs.
You can also specify the error page according to the HTTP status code (if mode is set to ON)
The sample code is as follows:
1<customerrors mode=" on"defaultredirect="genericerrorpage.htm">2<error statuscode="403"redirect="403.htm"/>3<error statuscode="404"redirect="404.htm"/>4</customErrors>
View Code
7. httphandlers
The user's request is handed to the appropriate handler based on the URL of the user request and the HTTP verb.
The sample code is as follows:
1 2 <add path="common/*.txt " verb=" *" type="System.Web.HttpForbiddenHandler"/>3
View CodeConfigure the application System.Web.HttpForbiddenHandler to process the TXT type file under Common, that is, to disable access to the file.
The actual use of the process, first put this configuration section in <system.web>, the results of local browsing operation error.
For the cause of the error is only a general feeling is the server processing mechanism is IIS or local webserver caused by the difference, not yet know why, this follow-up blog in-depth study. However, the workaround for the error message is clearly identified-"Migrating the configuration to the System.webserver/handlers section", so the code is modified as follows:
1<system.webServer>2<modules>3<remove name="FormsAuthenticationModule"/>4</modules>56<add name="HandlerName"Path="Common/*.txt"verb="*"Type="System.Web.HttpForbiddenHandler"/>78</system.webServer>
View CodeWhere handler part for the new, add a page, the page placed hyperlinks to access common under TXT file, the page as expected to jump to the friendly error handling page.
8. HttpRuntime
Used to set the ASP. NET HTTP Runtime
The sample code is as follows:
1 "4.5" executiontimeout="60 " maxrequestlength="40960" apprequestqueuelimit="100 " />
View CodeSet the target Framework version to 4.5, with a maximum time-out of 60s, a maximum concurrent request of 100, and a maximum upload file of 40M.
9. Pages
Used to represent settings on a specific page.
The sample code is as follows:
1<pages buffer="true"Enableviewstatemac="true"validaterequest="true">2<namespaces>3<addnamespace="System.Web.Optimization"/>4<addnamespace="Microsoft.AspNet.Identity"/>5</namespaces>6<controls>7<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms"tagprefix="webopt"/>8</controls>9</pages>
View CodeProperty
Buffer: Whether HTTP response buffering is enabled.
enableViewStateMac: Whether the view state of the page is checked for computer authentication to prevent user tampering.
ValidateRequest: Whether to verify that the user input contains a cross-site scripting attack or a SQL injection attack vulnerability.
Child elements
Controls: defines the collection of register directives and namespaces where the tag prefix resides.
Namespaces: defines a collection of import directives that will be used during assembly precompilation.
Ten. SessionState
Used to configure session state for the current application
The sample code is as follows:
1<sessionstate cookieless="false"timeout=" -"Mode="InProc"Customprovider="Defaultsessionprovider">2<providers>3<add name="Defaultsessionprovider"Type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, version=1.0.0.0, Culture=neutral, Publickeytoken=31bf3856ad364e35"Connectionstringname="defaultconnection"/>4</providers>5</sessionState>
View CodeThe above configuration settings enable cookies in the application, save session state in the process, and specify a session timeout of 30 minutes.
Where the mode value includes several options:
Custom: Stores session-state data using customized data.
InProc: The default value, which is stored by the ASP. NET worker process to store session state data, is faster, but consumes less memory and is not suitable for storing large user session data.
OFF: Disables session state.
SQL Server: Saves session state data using an out-of-process SQL database.
StateServer: Use the out-of-process ASP. NET State Service to store session state data.
Globalization.
Configure the globalization settings for your application.
The sample code is as follows:
1 <globalization fileencoding="utf-8" requestencoding="utf-8 "responseencoding="utf-8"/>
View Codefileencoding: Sets the storage encoding for ASPX, ASMX, asax files.
RequestEncoding: Sets the encoding of the client request.
ResponseEncoding: Sets the encoding of the service-side response.
Summary: A small one of the Web. config is really all-encompassing, this is only part of the configuration section, the other configuration sections are added in succession, at the same time for each configuration section and there are many points to learn, the road long its repair, efforts!
Web. config detailed