Tuesday, November 4, 2008
ASP.NET Optimization
* An improved process model.
* Compilation of requested pages and automatic storage on the server.
* ASP.NET-specific performance counters.
* Web application testing tools.
ASP.NET also gives you the ability to create Web applications that can handle the demands of processing large numbers of requests simultaneously.
In This Section
ASP.NET Performance Overview
Introduces the performance improvements offered by ASP.NET and outlines the main concepts of performance tuning for Web applications.
Developing High-Performance ASP.NET Applications
Details techniques that can help you develop ASP.NET Web applications with fast response times and high levels of throughput.
Monitoring ASP.NET Application Performance
Provides a brief overview of the tools and methods that you can use to monitor your ASP.NET Web applications, as well as a list of the performance counters that ship with ASP.NET.
Related Sections
ASP.NET Caching Features
Outlines the caching mechanisms that ASP.NET offers.
Monitoring Performance Thresholds
Describes how to use the performance counters that are delivered with the .NET Framework, as well as how to create your own PerformanceCounter objects to customize the way you monitor your applications, services, and drivers.
ASP.NET Performance Overview
Creating Web applications that respond to user requests quickly, even when a large number of requests are being processed on the server, has been a challenge for developers and IT personnel since the Internet began. Monitoring Web site performance is something that all Internet and intranet developers need to be able to do. ASP.NET was designed with this in mind.
The ASP.NET model provides a number of built-in performance enhancements that are not included in earlier versions of ASP. Particularly, there are two enhancements involved in processing HTTP requests. First, when an ASP.NET page is requested for the first time, an instance of the Page class is dynamically compiled. (In earlier versions of ASP, page code was interpreted for requests in the order that they appeared on the page.) The common language runtime just-in-time (JIT) compiles ASP.NET managed page code to the native code of the processing server at run time. Second, when the Page instance has been compiled for the first request, it is cached on the server. For each subsequent request for that page, the cached instance of the class is executed. After the initial request, the Page class is recompiled only when the original source for the page or one of its dependencies has changed.
In addition, ASP.NET caches internal objects, such as server variables, to speed user code access. As a part of the .NET Framework, ASP.NET benefits from the performance enhancements provided by the common language runtime, including the previously mentioned JIT compiling, a fine-tuned common language runtime for both single and multiprocessor computers, and so on.
These enhancements, unfortunately, cannot protect you from writing code that does not perform well when a large number of HTTP requests are processed by your application simultaneously. You must test your application to ensure that it meets the demands of its users. There are four common performance measures that you can test to ensure that your application is performing well.
Execution Time
The time it takes to process a request, usually measured between the first byte and the last byte returned to the client from the server. Execution time directly affects the throughput calculation.
Response Time
The length of time between when a request is requested and when the first byte is returned to the client from the server. This is often the most perceptible aspect of performance to the client user. If an application takes a long time to respond, the user can become impatient and go to another site. The response time of an application can vary independently of (even inversely to) the rate of throughput.
Scalability
The measurement of an application's ability to perform better as more resources (memory, processors, or computers) are allocated to it. Often, it is a measurement of the rate of change of throughput with respect to the number of processors.
Throughput
The number of requests a Web application can serve per unit of time, often measured in requests per second. Throughput can vary, depending on the load (number of client threads) applied to the server. This is usually considered the most important performance metric to optimize.
To write applications that perform well, it is important to maintain a balance of these metrics. No single measurement can characterize how your application will behave under varying circumstances, but several measurements taken together can show how well your application is performing. For more information about taking measurements of this kind, as well as information about the performance counters provided with ASP.NET, see Monitoring ASP.NET Application Performance
Monitoring ASP.NET Application Performance
There are a number of tools available to help you test and monitor the performance of your Web application. Microsoft Visual Studio .NET provides Application Center Test 1.0 (ACT), which simulates a large group of users by opening multiple connections to a Web server and rapidly sending HTTP requests. ASP.NET includes a number of performance counters that you can use to track the execution of your application. You can also use the built-in ASP.NET tracing feature to track code execution for a page or an application.
ACT is designed to stress test Web servers and to analyze performance and scalability problems with Web applications. For more information about ACT, either install Visual Studio .NET and open the ACT documentation, or perform a search on MSDN at http://msdn.microsoft.com.
Unlike traditional Active Server Pages (ASP), which exposed performance counters globally for the entire server computer, most of the ASP.NET performance counters are exposed per application. In the System Monitor tool (PerfMon), the per-application counters are available under the ASP.NET Applications performance object. If there are multiple applications on the server, you need to select a particular application instance when selecting a counter to monitor. However, there is a special __Total__ application instance in PerfMon that aggregates the counter values for all applications on a server. __Total__ is usually a sum of the counter values.
ASP.NET also exposes global-only counters that are not bound to a particular application instance. These counters are located under the ASP.NET performance object. To view the total available counters for ASP.NET on a Windows 2000 Server computer, use the following steps.
To view the available ASP.NET counters on a Windows 2000 Server computer
1. From the Start button, point to Programs, point to Administrative Tools, and then click Performance.
2. In PerfMon click View Report.
3. Click Add.
4. Select ASP.NET Applications, select All counters, then click OK.
5. Select ASP.NET System, select All counters, then click OK.
To view the available ASP.NET counters on a Windows XP computer with IIS installed
1. From the Start button, click Run.
2. Enter perfmon in the Open text box and then click OK.
3. In PerfMon click View Report.
4. Click Add.
5. Select ASP.NET Applications, select All counters, then click OK.
6. Select ASP.NET System, select All counters, then click OK.
For information about each of the ASP.NET system and ASP.NET application performance counters, see Performance Counters for ASP.NET.
ASP.NET also includes a trace feature that can show you important timing information between successive trace output statements, as well as information about the server control hierarchy, the amount of view state used, and the render size of controls on your page. For more information about tracing, see ASP.NET Trace.
Because ASP.NET is running on top of the common language runtime, it is possible to profile a Web page completely, from its entry point through any middle tier objects and to its end. This kind of profiling was not possible in ASP and provides a great tool for performance work in ASP.NET. Moreover, all common language runtime profilers are able to profile ASP.NET pages. Given the profiling services of the common language runtime, there is no need to instrument one's code beforehand; it is done at run time. For more information about profilers, see Debugging and Profiling Applications.
There are two major types of profilers: call-attributed profilers and sampling profilers. Call–attributed profilers allow you to view all method calls for a page or application and can give specific timings for each method call and any child method call it may contain. This is the most useful type of profiling for analyzing code paths and trying to trim them. However, if execution runs through any code path that has not been instrumented (for example when COM or native methods are called from ASP.NET), the profiler cannot keep track of when the methods were called. In such a case, the profiler attributes them to the last method that contains instrumentation code. For more information on including instrumentation in your code, see Debugging and Profiling Applications.
A sampling profiler is different in that no instrumentation needs to be done beforehand. Such a profiler essentially samples the CPU either at specified intervals or upon CPU interrupts and keeps track of what code is executing. It can then provide the user with a view of what code was most often executing during that period of time. This type of profiling is most useful for troubleshooting lock/resource contentions and performance bottlenecks in the code.
When you are doing steady-state running analysis, it is often best to ignore the first request and any one-time initialization costs for objects. For example, when requesting an ASP.NET page for the first time, there is always the cost of compiling an instance of the Page class. Once that has occurred, performance will improve for subsequent requests.
For more information about performance monitoring in the .NET Framework, see Monitoring Performance Thresholds.
Performance Counters for ASP.NET
ASP.NET supports two groups of performance counters: system and application. The former is exposed in PerfMon in the ASP.NET performance counter object; the latter is exposed in the ASP.NET Applications performance object. There is a significant difference between the State Server Sessions counters found in the ASP.NET performance object, which apply only to the server computer on which the state server is running, and the Sessions counters found in the ASP.NET Applications performance object, which apply only to user sessions that occur in process.
Note The value associated with each performance counter is updated every 400 milliseconds. When creating a monitoring application, be sure to take this time lapse into account so that your code does not use an obsolete counter value. For more information, see Creating System Monitoring Components.
When monitoring the performance of your ASP.NET Web applications, you should always track the following performance counters.
Performance object Performance counter
ASP.NET Application Restarts
ASP.NET Requests Queued
ASP.NET Worker Process Restarts
ASP.NET Applications Errors Total
ASP.NET Applications Requests/Sec
Processor % CPU Utilization
The % CPU Utilization counter monitors CPU utilization on the Web server computer. Low CPU utilization or the inability to maximize CPU utilization regardless of client load can signify contention for a lock or a resource in your Web application.
In addition, the following performance counters can be valuable in determining problems with your Web applications' performance.
Performance object Performance counter
ASP.NET Applications Pipeline Instance Count
.NET CLR Exceptions # of Exceps Thrown
System Context Switches/sec
The # of Exceps Thrown counter displays the number of exceptions thrown in an application, since these can have performance implications. Some code paths, however, rely on exceptions for their proper functioning. For example, the HttpResponse.Redirect method does its work by throwing an uncatchable exception, ThreadAbortException. As such, it may be more useful to track this value with the Errors Total counter to see if the exception generated an error on the application.
The Context Switches/sec counter measures the rate at which thread contexts are switched by all CPUs in the Web server computer. A high number for this counter usually indicates either high contention in locks or many switches between user and kernel mode by the thread. Further investigation with sampling profilers and other tools may be warranted.
The ASP.NET and ASP.NET Applications performance counters are detailed in the following lists.
ASP.NET System Performance Counters
ASP.NET supports the following ASP.NET system performance counters. These aggregate information for all ASP.NET applications on a Web server computer, or they apply generally to a system of ASP.NET servers running the same applications. These can include Web farms and Web gardens.
Application Restarts
The number of times that an application has been restarted during the Web server's lifetime. Application restarts are incremented with each Application_OnEnd event. An application restart can occur because of changes to the Web.config file, changes to assemblies stored in the application's \bin directory, or too many changes in Web Forms pages. Unexpected increases in this counter can mean that unforeseen problems are causing your Web application to shut down. In such circumstances you should investigate as soon as possible.
Note This value is reset every time the Internet Information Services (IIS) host is restarted.
Application Running
The number of applications running on the server computer.
Requests Disconnected
The number of requests that have been disconnected due to a communication failure.
Requests Queued
The number of requests waiting for service from the queue. When this number starts to increment linearly with respect to client load, the Web server computer has reached the limit of concurrent requests that it can process. The default maximum for this counter is 5,000. You can change this setting in the computer's Machine.config file.
Requests Rejected
The total number of requests not executed because of insufficient server resources to process them. This counter represents the number of requests that return a 503 HTTP status code, indicating that the server is too busy.
Request Wait Time
The number of milliseconds that the most recent request waited for processing in the queue.
Session State Server Connections Total
The total number of session-state connections to the computer on which out-of-process session-state data is stored.
Session SQL Server Connections Total
The total number of session-state connections to the Microsoft SQL Server database in which session-state data is stored.
State Server Sessions Abandoned
The number of user sessions that have been explicitly abandoned. These are sessions that are ended by specific user actions, such as closing the browser or navigating to another site. This counter is available only on the computer where the state server service (aspnet_state) is running.
State Server Sessions Active
The number of currently active user sessions. This counter is available only on the computer where the state server service (aspnet_state) is running.
State Server Sessions Timed Out
The number of user sessions that have become inactive through user inaction. This counter is available only on the computer where the state server service (aspnet_state) is running.
State Server Sessions Total
The number of sessions created during the lifetime of the process. This counter is the cumulative value of State Server Sessions Active, State Server Sessions Abandoned, and State Server Sessions Timed Out. This counter is available only on the computer where the state server service (aspnet_state) is running.
Worker Process Restarts
The number of times a worker process has been restarted on the server computer. A worker process can be restarted if it fails unexpectedly or when it is intentionally recycled. In the case of unexpected increases in this counter you should investigate as soon as possible.
Worker Process Running
The number of worker processes running on the server computer.
ASP.NET Application Performance Counters
ASP.NET supports the following application performance counters, which you can use to monitor the performance of a single instance of an ASP.NET application. A unique instance appears for these counters, named __Total__, which aggregates counters for all applications on a Web server (similar to the global counters described in the first section of this topic). The __Total__ instance is always available. The counters will display zero when no applications are present on the server.
Anonymous Requests
The number of requests that are using anonymous authentication.
Anonymous Requests/Sec
The number of requests per second that are using anonymous authentication.
Cache Total Entries
The total number of entries in the cache. This counter includes both internal use of the cache by the ASP.NET page framework and external use of the cache through exposed APIs.
Cache Total Hits
The total number of hits from the cache. This counter includes both internal use of the cache by the ASP.NET page framework and external use of the cache through exposed APIs.
Cache Total Misses
The number of failed cache requests per application. This counter includes both internal use of the cache by ASP.NET and external use of the cache through exposed APIs.
Cache Total Hit Ratio
The ratio of hits to misses for the cache. This counter includes both internal use of the cache by ASP.NET and external use of the cache through exposed APIs.
Cache Total Turnover Rate
The number of additions and removals to the total cache per second. It is useful in helping determine how effectively the cache is being used. If the turnover is large, the cache is not being used efficiently.
Cache API Entries
The total number of entries in the application cache.
Cache API Hits
The total number of hits from the cache when it is accessed through only the external cache APIs. This counter does not track any use of the cache internally by ASP.NET.
Cache API Misses
The total number of failed requests to the cache when accessed through the external cache APIs. This counter does not track any use of the cache internally by ASP.NET.
Cache API Hit Ratio
The cache hit-to-miss ratio when accessed through the external cache APIs. This counter does not track any use of the cache internally by ASP.NET.
Cache API Turnover Rate
The number of additions and removals to the cache per second, when used through the external APIs (excluding internal use by the ASP.NET page framework). It is useful in helping determine how effectively the cache is being used. If the turnover is large, then the cache is not being used effectively.
Compilations Total
The total number of compilations that have taken place during the lifetime of the current Web server process. This occurs when a file with an .aspx, .asmx, .ascx, or .ashx extension, or a code-behind source file, is dynamically compiled on the server.
Note This number will initially climb to a peak value as requests are made to all parts of an application. Once a compilation occurs, however, the resulting binary is saved to disk, where it is reused until its source file changes. This means that, even in the event of a process restart, the counter can remain at zero (inactive) until the application is modified or redeployed.
Debugging Requests
The number of requests that occur while debugging is enabled.
Errors During Preprocessing
The number of errors that occurred during parsing. Excludes compilation and run-time errors.
Errors During Compilation
The number of errors that occur during dynamic compilation. Excludes parser and run-time errors.
Errors During Execution
The total number of errors that occur during the execution of an HTTP request. Excludes parser and compilation errors.
Errors Unhandled During Execution
The total number of unhandled errors that occur during the execution of HTTP requests.
Note An unhandled error is any uncaught run-time exception that escapes user code on the page and enters the ASP.NET internal error-handling logic. Exceptions to this rule occur when:
* Custom errors are enabled, an error page is defined, or both.
* The Page_Error event is defined in user code and either the error is cleared (using the HttpServerUtility.ClearError Method method) or a redirect is performed.
Errors Unhandled During Execution/Sec
The number of unhandled exceptions per second that occur during the execution of HTTP requests.
Errors Total
The total number of errors that occur during the execution of HTTP requests. Includes any parser, compilation, or run-time errors. This counter is the sum of the Errors During Compilation, Errors During Preprocessing, and Errors During Execution counters. A well functioning Web server should not generate errors. If errors occur in your ASP.NET Web application, they may skew any throughput results because of very different code paths for error recovery. Investigate and fix any bugs in your application before performance testing.
Errors Total/Sec
The number of errors per second that occur during the execution of HTTP requests. Includes any parser, compilation, or run-time errors.
Output Cache Entries
The total number of entries in the output cache.
Output Cache Hits
The total number of requests serviced from the output cache.
Output Cache Misses
The number of failed output-cache requests per application.
Output Cache Hit Ratio
The percentage of total requests serviced from the output cache.
Output Cache Turnover Rate
The number of additions and removals to the output cache per second. If the turnover is large, the cache is not being used effectively.
Pipeline Instance Count
The number of active request pipeline instances for the specified ASP.NET application. Since only one execution thread can run within a pipeline instance, this number gives the maximum number of concurrent requests that are being processed for a given application. In most circumstances it is better for this number to be low when under load, which signifies that the CPU is well utilized.
Request Bytes In Total
The total size, in bytes, of all requests.
Request Bytes Out Total
The total size, in bytes, of responses sent to a client. This does not include standard HTTP response headers.
Requests Executing
The number of requests currently executing.
Requests Failed
The total number of failed requests. Any and all status codes greater than or equal to 400 will increment this counter.
Note Requests that cause a 401 status code will increment this counter and the Requests Not Authorized counter. Requests that cause a 404 or 414 status code will increment this counter and the Requests Not Found counter. Requests that cause a 500 status code will increment this counter and the Requests Timed Out counter.
Note The equivalent ASP counter would also increment on requests rejected, which cannot be done (because the rejection is done by IIS and not the process model).
Requests Not Found
The number of requests that failed because resources were not found (status code 404, 414).
Requests Not Authorized
The number of requests that failed due to no authorization (status code 401).
Requests Succeeded
The number of requests that executed successfully (status code 200).
Requests Timed Out
The number of requests that timed out (status code 500).
Requests Total
The total number of requests since the service was started.
Requests/Sec
The number of requests executed per second. This represents the current throughput of the application. Under constant load, this number should remain within a certain range, barring other server work (such as garbage collection, cache cleanup thread, external server tools, and so on).
Sessions Active
The number of sessions currently active. This counter is supported only with in-memory session state.
Sessions Abandoned
The number of sessions that have been explicitly abandoned. This counter is supported only with in-memory session state.
Sessions Timed Out
The number of sessions that timed out. This counter is supported only with in-memory session state.
Sessions Total
The number of sessions timed out. This counter is supported only with in-memory session state.
Transactions Aborted
The number of transactions aborted.
Transactions Committed
The number of transactions committed.
Transactions Pending
The number of transactions in progress.
Transactions Total
The total number of transactions since the service was started.
Transactions/Sec
The number of transactions started per second.
See Also
Monitoring Performance Thresholds | Monitoring ASP.NET Application Performance
ASP.NET introduces new functionality that allows you to view diagnostic information about a single request for an ASP.NET page simply by enabling it for your page or application. Called tracing, this feature also allows you to write debug statements directly in your code without having to remove them from your application when it is deployed to production servers. You can write variables or structures in a page, assert whether a condition is met, or simply trace through the execution path of your page or application.
In order for these messages and other tracing information to be gathered and displayed, you must enable tracing for the page or application. When you enable tracing, two things occur:
- ASP.NET appends a series of diagnostic information tables immediately following the page's output. The information is also sent to a trace viewer application (if you have enabled tracing for the application).
- ASP.NET displays your custom diagnostic messages in the Trace Information table of the appended performance data.
Diagnostic information and tracing messages that you specify are appended to the output of the page that is sent to the requesting browser. Optionally, you can view this information from a separate trace viewer (Trace.axd) that displays trace information for every page in a given application. This information can help you to clarify errors or undesired results as ASP.NET processes a page request.
Trace statements are processed and displayed only when tracing is enabled. You can control whether tracing is displayed to a page, to the trace viewer, or both.
In This Section
- Enabling Tracing for a Page
- Explains how to enable tracing for a page, include trace statements in page output, and interpret trace messages.
- Writing Trace Messages
- Describes how to use the TraceContext.Write and TraceContext.Warn methods to write statements to the trace log.
- Enabling Application-Level Tracing
- Details how you can enable tracing for an entire application through the ASP.NET configuration system. It also describes how to use the trace viewer, an HTTP module that you can access from your Web browser.
- Reading Trace Information
- Details the information available to you when you view trace information that is added to the page or to the trace viewer.
Related Sections
- Creating ASP.NET Web Applications
- Introduces the features of ASP.NET and outlines what you can accomplish by programming with them.
- TraceContext Class
- Captures and presents execution details about a Web request.
You can control whether tracing is enabled or disabled for a page with the Trace attribute of the @ Page directive. Regardless of whether you write messages to the trace log, when you enable tracing and the page is requested, ASP.NET appends a series of tables containing performance information about the page request.
Tracing is disabled by default. If you do not include a Trace attribute in your page, trace information is not gathered, and trace statements you write do not appear on the page.
To enable tracing for a page
- Include an @ Page directive at the beginning of your .aspx file. Include the Trace attribute, and set its value to true.
<%@ Page Trace="true" %>
Security Note When tracing is enabled for a page, trace information is displayed on any browser that makes a request for the page from the server. Tracing displays sensitive information, such as the values of server variables, and can therefore represent a security threat. Be sure to disable page tracing for the page before porting your application to a production server. You can do this by setting the Trace attribute to false, or by removing it.
- Optionally, include the TraceMode attribute to specify the order in which you want your trace messages to appear. Set the attribute to SortByTime to sort the messages in the order in which they are processed. Set the attribute to SortByCategory to sort them by the categories you specified in the Trace.Warn and Trace.Write method calls in your page or server control code.
The following example, when included at the top of a page, sorts the trace messages of the page and of the server control contained in that page by category.
<%@ Page Language="VB" Trace="True" TraceMode="SortByCategory" %>
The following screen shot illustrates a page with trace information appended to the end of the page output.
Page tracing

ASP.NET includes a Trace object (similar to the Response, Request, and Context objects) that allows you to write debug statements that appear when you enable tracing for a page or for the entire application.
ASP.NET uses the TraceContext class to store information about a request, its control hierarchy, and trace information. Trace information includes some of the life-cycle stages of a page request and any custom statements you choose to include. The TraceContext class is available to Web Forms pages through the Page.Trace property. When you create custom ASP.NET server controls by extending the Control class, you can access the TraceContext class through the Control.Context property using Control.Context.Trace syntax. However, if you want to include trace statements from files other than a page or control, such as your application's Global.asax file or a class that extends the IHttpHandler interface, you must use the HttpContext.Current property to access the TraceContext class. In this case, use HttpContext.Current.Trace syntax.
The TraceContext class provides two methods, Write and Warn, which allow you to write statements to the trace log. Each method is overloaded and allows you to specify a tracing category, a text message, and optional error information. The only difference between these methods is that the Warn method displays its text in red.
Note When you specify a category in a call to the Write or Warn method, you can use this category to sort trace statements. For more information, see Enabling Tracing for a Page and Enabling Application-Level Tracing.
Each of these methods is overloaded and has three versions. If you include only one string argument when you call Warn or Write, ASP.NET treats this as a message. If you include two arguments, the first is treated as a category, which you can use to sort where your messages appear in the Trace Information table that is displayed when tracing is enabled. The third argument is of type Exception and contains error information for the request, if there is any.
These trace statements and the rest of the tracing information are displayed in a requesting browser when you enable tracing for the page or entire application.
Security Note When tracing is enabled for a page, trace information is displayed on any browser that makes a request for the page from the server. Tracing displays sensitive information, such as the values of server variables, and can therefore represent a security threat. Be sure to disable page tracing for the page before porting your application to a production server. You can do this by setting the Trace attribute to false, or by removing it.
The following screen shot illustrates custom trace statements, rendered to the Trace Information table, when tracing is enabled for a page. The Warn method is used to generate the first message in red text, with a category of Render and a message of Text is about to render!. The Write method is used to generate the second custom message with the same category, but with a message of Text finished rendering!.
Trace statements in a page

To write custom trace messages to the trace log from a page
- In your page's code-declaration block or code-behind class, call one of the TraceContext methods, using the Trace property.
- Specify the optional category parameter for your trace statement. You can use this category to sort trace statements when they are displayed.
- Specify the message parameter for your trace statement. This can be a string or a method.
- Specify the optional errorInfo parameter that contains information about any errors in the page.
The following example of the TraceContext.Warn method defines a category of
Renderand a trace message ofText is about to render.[C#]Trace.Warn("Render", "Text is about to render.");
[Visual Basic]
Trace.Warn("Render", "Text is about to render.")
To write custom trace message to the trace log from a custom server control
- In your server control's code, call one of the TraceContext methods using the Context property.
- Specify the optional category parameter for your trace statement. You can use this category to sort trace statements when they are displayed.
- Specify the message parameter for your trace statement.
- Specify the optional errorInfo parameter that contains information about any errors in the page.
The following example uses the TraceContext.Write method to write custom statements to a server control's trace log. The category is
My Class, and the message isThis is a simple trace statement.
There are occasions when you want to pass statements to the Write or Warn methods only when tracing is enabled. The TraceContext object has a Boolean property, IsEnabled, that allows you to conditionally call these methods.
To write trace messages to the log only when tracing is enabled
Create an If statement that checks whether tracing is enabled for the page or application to which your code belongs, then a conditional statement to be executed when the Trace.IsEnabled property returns true.The following example confirms that tracing is enabled for a page, then uses the Write method to write a selected number of books from a database to the Trace Information table.
[C#] |
If (Trace.IsEnabled) { |
You can enable tracing for an entire application in the Web.config file in the application's root directory. By default, application-level tracing can be viewed only on the local Web server computer. You must set the localOnly attribute to false in the Web.config file to make application-level trace information visible from remote computers.
CAUTION To help keep your Web application secure, use the remote trace capability only when you are developing or deploying your application. Be sure to disable it before you transfer your application onto production Web servers. To disable remote tracing, set the localOnly attribute to true in the Web.config file.
The following example shows an application trace configuration that collects trace information for up to 40 requests and allows browsers on computers other than the origin server to display the trace viewer.
When you enable tracing for an application, ASP.NET collects trace information for each request to the application, up to the maximum number of requests you specify. The default number of requests is 10. When the trace viewer reaches its request limit, the application stops storing trace requests.
Note When you enable tracing for an entire application in the Web.config file, trace information is gathered and processed for each page in that application. To disable tracing for a particular page in the application, set the Trace attribute in that page's @ Page directive to false. Any TraceContext.Write or TraceContext.Warn statements that you include in a page's code are stored and returned to the trace viewer only.
If you want trace information to appear at the end of the page that it is associated with, set the pageOutput attribute in the tracing configuration section of the Web.config file to true. If you want tracing information to be displayed only in the trace viewer, set this attribute to false. If you enable application-level tracing, but you do not want trace information displayed for some pages of the application, use the @ Page directive to set the Trace attribute to false for those pages you do not want trace information displayed in.
For more information about configuring your ASP.NET application, see ASP.NET Configuration.
The following are all the attributes you can use to modify the behavior of application-level tracing.
| Attribute | Description |
|---|---|
| enabled | true if tracing is enabled for the application; otherwise, false. The default is false. |
| pageOutput | true if trace information is displayed both on an application's pages and in the .axd trace utility; otherwise, false. The default is false. Note Pages that have tracing enabled are not affected by this setting. |
| requestLimit | Number of trace requests to store on the server. The default is 10. |
| traceMode | Indicates whether trace information is displayed in the order in which it was processed (SortByTime) or alphabetically by user-defined category (SortByCategory). The default is SortByTime. |
| localOnly | true if the trace viewer (Trace.axd) is available only on the host Web server; otherwise, false. The default is true. |
To enable tracing for an application
- If you have not done so already, create a text file, name it Web.config, and save it to your application's root directory.
- Between the opening and closing tags of the
<configuration>element, add the opening and closing tags of a<system.web>element. - Between the
<system.web>element tags, add a<trace>element, which is self-closing. - In the
<trace>element, declare the enabled attribute and set it to true. - Declare other optional attributes to modify your application's trace behavior, as you want.
For example, the following application trace configuration collects trace information for up to 40 requests and allows browsers on computers other than the origin server to display the trace viewer.
Note The ASP.NET configuration system is case-sensitive. All single-word configuration sections are lowercase, whereas sections or attributes that are concatenations of two words must be camel-cased. For example,
requestLimitis a valid attribute name, butrequestlimitcauses a parser error.
Viewing Trace Information with the Trace Viewer
Once you have enabled tracing for your application, each page in the application will execute any trace statements that it contains when it is requested. You can view these statements and the additional trace information in the trace viewer by requesting Trace.axd from the root of your application directory.
Note When you enable tracing for an application, you can view the trace statements, and additional information, in any page in the application by setting the pageOutput attribute to true in the Web.config file.
The trace viewer allows you to choose a specific request from the pages that have been requested from your application. The following screen shot shows a trace viewer that has had seven requests to its application since tracing was enabled.
Trace viewer

If multiple requests have arrived for an application that has tracing enabled, the trace viewer lists the requests in the order in which they were processed. The information on the opening page of the trace viewer includes the time of the request, the file requested, the status code of the request, the HTTP verb associated with the request, and a View Details link that allows you to see more detailed information about the request. The number of requests displayed will not exceed the requestLimit setting that you specified in the Web.config file.
To view trace details for a specific request
- Navigate to the trace viewer associated with your application.
For example, if the URL for your application is http://localhost/myapplication, navigate to http://localhost/myapplication/trace.axd to view the trace statistics for that application.
- Select the View Details link for the request that you want to investigate.
Once you have selected View Details, you view the same information that was appended to the page that had tracing enabled.
In some circumstances, you might want to remove all the requests stored in the trace viewer. Perhaps you want to track changes you made to files in your application, or you simply want to view information on other files than those associated with the currently displayed requests.
To clear requests from the trace viewer
- Navigate to the trace viewer associated with the application.
- Select the clear current trace link to remove all the requests stored in the trace viewer application.
Note The trace viewer tracks only requests made after you clear the log. Requests made after the request limit is reached and before you clear the log cannot be viewed.
Whether you choose to view trace information appended at the end of an ASP.NET page or in the trace viewer, the information displayed is the same. ASP.NET organizes the trace information in a series of tables that provide diagnostic information about the request that you are viewing.
Trace information appears in the following order once you have enabled tracing for a page or application.
Request Details
| Value | Description |
|---|---|
| Session ID | The session identification for the specified request. |
| Time of Request | The time the request was made. |
| Request Encoding | The character encoding for the request. |
| Request Type | The HTTP method used. Can be GET or POST. |
| Status Code | The status-code value associated with the response. For more information, see RFC 2616 about HTTP 1.1 at www.w3c.org. |
| Response Encoding | The character encoding for the response. |
Trace Information
| Value | Description |
|---|---|
| Category | The custom trace category that you specified in a TraceContext.Warn or TraceContext.Write method call. |
| Message | The custom trace message that you specified in a TraceContext.Warn or TraceContext.Write method. |
| From First (s) | The time, in seconds, since the first message was displayed. |
| From Last (s) | The time, in seconds, since the most recent message was displayed. |
Control Tree
| Value | Description |
|---|---|
| Control ID | The identification for the control. If you have not specified an ID property for the control, ASP.NET generates an ID using the UniqueID property. |
| Type | The fully qualified type of the control. |
| Render Size bytes | The size, in bytes, of the rendered control (including child controls). This is the size of the actual HTML, XML, or other format that is sent to the browser client. |
| Viewstate Size bytes | The size, in bytes, of the control's view state (excluding child controls). For more information, see Web Forms State Management. |
Cookies Collection
| Value | Description |
|---|---|
| Name | The name of the cookie. |
| Value | The value of the cookie, or subkeys/values if multivalued. |
| Size | The size, in bytes, of the cookie. |
Headers Collection
| Value | Description |
|---|---|
| Name | The name of the header. |
| Value | The value of the header. |
Form Collection
| Value | Description |
|---|---|
| Name | The name of the form variable. |
| Value | The value of the form variable. |
Server Variables
| Value | Description |
|---|---|
| Name | The name of the server variable. |
| Value | The value of the server variable. |
Subscribe to Comments [Atom]
