✅ Tracing in ASP.NET
🔷 What is Tracing?
Tracing in ASP.NET is a diagnostic feature that allows developers to monitor the execution of a web application by logging detailed information such as:
- Page lifecycle events
- Variable values
- Method execution
- Request/response details
- Errors or exceptions
🧪 Useful during development and debugging to understand application behavior or identify issues.
🔷 Why Use Tracing?
| Benefit | Description |
|---|---|
| 🔍 Debugging | Helps track execution flow and catch bugs |
| 📋 Logging | Records variable values, page events, errors |
| 📈 Performance Monitoring | Measures execution time of operations |
| 🧰 Post-deployment Diagnostics | Enables diagnostics in production without modifying code |
🔷 Types of Tracing in ASP.NET
- Page-Level Tracing – Enabled for individual pages
- Application-Level Tracing – Enabled for all pages in the application
🔷 1. Page-Level Tracing
✅ How to Enable:
In the .aspx page, add:
<%@ Page Trace="true" %>
📌 This will display trace information at the bottom of the page.
✅ Example Usage in Code:
Trace.Write("Debug", "Page_Load started");
Trace.Warn("Warning", "Potential issue here");
🔷 2. Application-Level Tracing
✅ Enable in web.config:
<configuration>
<system.web>
<trace enabled="true"
pageOutput="false"
requestLimit="10"
localOnly="false" />
</system.web>
</configuration>
| Attribute | Description |
|---|---|
enabled |
Turns tracing on/off |
pageOutput |
If true, shows trace info on page |
requestLimit |
How many requests to keep in memory |
localOnly |
If false, remote clients can access trace viewer |
✅ View Trace Results:
Navigate to:
http://your-app/trace.axd
This shows a web-based trace viewer with request details, events, headers, etc.
🔷 Trace Class Methods
| Method | Description |
|---|---|
Trace.Write() |
Logs a message |
Trace.Warn() |
Logs a warning message (highlighted) |
Trace.IsEnabled |
Checks if tracing is active |
🔷 Example:
if (Trace.IsEnabled)
{
Trace.Write("TraceTest", "This is a trace message");
Trace.Warn("TraceTest", "This is a warning trace");
}
✅ Key Data in Trace Output:
- Request details (URL, timestamp)
- Control tree
- Session and cookie data
- ViewState size
- Server variables
- Custom messages from code
🔐 Security Note:
- Don't leave tracing enabled in production unless needed.
- Avoid logging sensitive data (like passwords) in trace.
✅ Summary
| Feature | Description |
|---|---|
| 🔎 Tracing | Logs detailed info for debugging |
| 📄 Page-Level | Trace="true" in .aspx file |
| ⚙ App-Level | Set in web.config, view via /trace.axd |
| 🛠 Useful For | Debugging, performance tracking, diagnostics |
✅ HTTP Modules in ASP.NET
🔷 What is an HTTP Module?
An HTTP Module is a component in the ASP.NET request processing pipeline that lets you intercept, inspect, and modify incoming requests and outgoing responses.
Think of it like a filter that sits between the client and the server — it listens to every request.
🔷 Purpose of HTTP Modules
| Function | Description |
|---|---|
| 🔐 Authentication | Check login/session/token in the request |
| 🧾 Logging | Log details about each request/response |
| 📦 Compression | Compress content before sending to client |
| 🚧 Custom Headers | Add or modify HTTP headers |
| 🚨 Error Handling | Catch and handle application-level errors |
🔷 How HTTP Modules Work
- ASP.NET handles requests through a pipeline.
- HTTP Modules are registered to hook into specific events in this pipeline.
- They implement the
IHttpModuleinterface.
🔷 Life Cycle Events an HTTP Module Can Handle:
| Event | Purpose |
|---|---|
BeginRequest |
Fired when the request starts |
AuthenticateRequest |
Authenticate the user |
AuthorizeRequest |
Authorize access |
AcquireRequestState |
Get session data |
PreRequestHandlerExecute |
Before page/controller executes |
EndRequest |
At the end of request processing |
Error |
When an unhandled exception occurs |
🔷 Creating a Custom HTTP Module
✅ Step 1: Create the Module Class
public class MyModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(OnBeginRequest);
context.EndRequest += new EventHandler(OnEndRequest);
}
public void OnBeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Write("BeginRequest triggered<br>");
}
public void OnEndRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Write("EndRequest triggered<br>");
}
public void Dispose() { }
}
✅ Step 2: Register Module in web.config
<configuration>
<system.web>
<httpModules>
<add name="MyModule" type="MyNamespace.MyModule" />
</httpModules>
</system.web>
</configuration>
For ASP.NET 4.0+, register under
<system.webServer>:
<system.webServer>
<modules>
<add name="MyModule" type="MyNamespace.MyModule" />
</modules>
</system.webServer>
🔷 Built-in HTTP Modules
| Module | Purpose |
|---|---|
FormsAuthentication |
Handles forms-based login |
UrlAuthorization |
Checks user permissions |
Session |
Manages session state |
OutputCache |
Handles caching responses |
✅ Summary
| Key Point | Explanation |
|---|---|
| 📌 Definition | Reusable components that intercept HTTP requests |
| 🔄 Events | Hook into request lifecycle (BeginRequest, EndRequest, etc.) |
| 🧱 Interface | Must implement IHttpModule |
| 📋 Uses | Authentication, logging, custom logic, compression, etc. |
✅ Custom HTTP Handlers in ASP.NET
🔷 What is an HTTP Handler?
An HTTP Handler is a component in ASP.NET that directly processes HTTP requests made to a web application. It acts as the endpoint for handling specific types of requests like .aspx, .ashx, images, or custom URLs.
Think of it as the “worker” that generates a response for a specific request.
🔷 Why Use Custom HTTP Handlers?
| Purpose | Example |
|---|---|
| Serve dynamic images | Generate charts, barcodes, CAPTCHA |
| Return JSON/XML data | Serve custom APIs |
| Serve files | Provide file download or preview logic |
| Log or audit requests | Record custom analytics |
🔶 How to Create a Custom HTTP Handler
✅ Step 1: Create a Class that Implements IHttpHandler
public class MyHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello from custom HTTP handler!");
}
public bool IsReusable
{
get { return false; }
}
}
ProcessRequest– Called when the handler is invoked.IsReusable– Whether this instance can be reused for another request.
✅ Step 2: Register in web.config
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="hello.handler" type="MyNamespace.MyHandler"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add name="MyHandler" path="hello.handler" verb="*" type="MyNamespace.MyHandler" resourceType="Unspecified" />
</handlers>
</system.webServer>
</configuration>
📌 Now, navigating to
http://localhost/hello.handlerwill execute your handler.
🔷 Using .ashx Shortcut
ASP.NET provides a simpler way to create handlers using .ashx files.
✅ Example:
File: HelloWorld.ashx
<%@ WebHandler Language="C#" Class="HelloWorld" %>
public class HelloWorld : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World from .ashx!");
}
public bool IsReusable { get { return false; } }
}
You don’t need to register .ashx files in web.config.
🔷 Comparison: Handler vs Module
| Feature | HTTP Handler | HTTP Module |
|---|---|---|
| 📌 Role | Final request processor | Pre/post processing |
| 🔄 Events | No events, only ProcessRequest() |
Can hook into lifecycle events |
| ⚙ Use Case | Serve content, files, images | Auth, logging, compression |
| 🧱 Interface | IHttpHandler |
IHttpModule |
✅ Summary
| Point | Description |
|---|---|
| 💡 What | Custom logic to handle specific HTTP requests |
| 🧱 Interface | Implements IHttpHandler |
| 🔧 Uses | APIs, file serving, images, data streams |
| 🔗 Access | Via custom extension like .handler or .ashx |
| 🧰 Tip | Use .ashx for simple handlers without extra config |