| ASP.NET Interview Questions-1 to 10 :👈 | 👉:ASP-NET Interview Questions-21 to 30 |
ASP.NET Interview Questions 11 to 20 |
11. Given One ASP.NET Application, How Many Application Objects Does It Have on a Single-Processor Box, a Dual-Processor Box, and a Dual-Processor Box with Web Gardening Enabled?
The classic interview answer concerns the ASP.NET application instance and its in-memory state within each worker process, not the number of physical CPU cores.
| Configuration | Typical number of application instances |
|---|---|
| Single-processor server with one worker process | One |
| Dual-processor server with one worker process | One |
| Dual-processor server with Web Gardening enabled and N worker processes configured | Typically N separate application instances, one per worker process |
A dual-processor machine does not automatically create two application objects. The number of application instances depends on application domains and worker-process configuration.
How does this affect design?
- Do not rely on static variables as shared storage across worker processes.
- Use an external shared cache or database for state that must be consistent across processes.
- Use appropriate session-state configuration when session continuity is required.
- Design initialization and background processing carefully so that each worker process does not accidentally duplicate work.
12. Are Threads Reused in ASP.NET Between Requests? Does Every HttpRequest Get Its Own Thread? Should You Use Thread Local Storage with ASP.NET?
Classic ASP.NET generally processes requests using threads from the .NET ThreadPool. Threads are reused to process different requests over time.
Therefore, every HttpRequest does not receive a permanently dedicated thread. A request is commonly processed on a ThreadPool thread, but the precise execution model depends on the request type, asynchronous operations, and hosting environment.
Should You Use Thread-Local Storage?
Usually, you should not use thread-local storage to maintain request-specific state in ASP.NET.
Thread-local data belongs to a physical thread, not to a logical request. Because threads are reused, a later request can run on the same thread and encounter stale thread-local values if cleanup is not handled correctly.
Asynchronous operations can also resume on a different thread, making thread-local state unsuitable for many request-scoped purposes.
Better options include:
HttpContext.Itemsfor data associated with a single classic ASP.NET request.- Dependency injection with an appropriate scoped lifetime in modern ASP.NET Core.
- Explicitly passing data between methods.
AsyncLocal<T>when logical asynchronous execution-context propagation is appropriate, with care around lifetime and shared mutable data.
13. Is the [ThreadStatic] Attribute Useful in ASP.NET? Are There Side Effects?
[ThreadStatic] marks a static field as thread-specific. Each thread receives its own separate storage for that field.
Example
public class RequestHelper
{
[ThreadStatic]
private static string _currentValue;
}
Each physical thread has its own copy of _currentValue.
Potential Problems in ASP.NET
- Threads are reused between requests, so values can leak logically from one request to another if not cleared.
- Static fields are not initialized separately by a normal static field initializer for each thread; other threads may observe the field's default value until it is assigned.
- Asynchronous work may continue on another thread, where a different thread-local value exists.
- It is easy to assume that a thread represents one request when that assumption is false.
Conclusion: [ThreadStatic] is useful for specific thread-affine scenarios, but it is generally not a suitable mechanism for ASP.NET request state.
14. Give an Example of How an HttpHandler Could Simplify a Design That Serves Check Images from an .aspx Page
An IHttpHandler handles an HTTP request and generates the response. It can be useful when an endpoint serves a specific resource, such as a dynamically generated check image or CAPTCHA image, rather than a full HTML page.
Instead of creating a complete Web Forms page such as CheckImage.aspx, an application can route requests to a dedicated handler.
Example Handler
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
public class CheckImageHandler : IHttpHandler
{
public bool IsReusable => false;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/png";
context.Response.Cache.SetCacheability(
HttpCacheability.NoCache);
using (var bitmap = new Bitmap(160, 50))
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.Clear(Color.White);
graphics.DrawString(
"Check",
new Font("Arial", 18),
Brushes.Black,
10,
10);
bitmap.Save(
context.Response.OutputStream,
ImageFormat.Png);
}
}
}
The handler can be mapped to a URL such as /CheckImage.ashx in a suitable ASP.NET Framework application.
Advantages
- No need to execute the full Web Forms page lifecycle.
- Direct control over the response content type and output stream.
- Clear separation between image generation and HTML page rendering.
- Useful for images, downloads, feeds, and other specialized endpoints.
Note: The example uses System.Drawing, which is suitable for classic Windows-based ASP.NET Framework scenarios. It is not the recommended cross-platform image-generation approach for modern .NET.
15. What Kinds of Events Can an HttpModule Subscribe To? What Influence Can It Have? What Can Be Done Without Recompiling the ASP.NET Application?
An IHttpModule participates in the ASP.NET Framework request pipeline and can subscribe to application lifecycle events.
Common Events
BeginRequest— the beginning of request processing.AuthenticateRequest— authentication processing.PostAuthenticateRequest— after authentication.AuthorizeRequest— authorization processing.ResolveRequestCache— request-cache resolution.AcquireRequestState— acquisition of session or other request state.PreRequestHandlerExecute— immediately before the selected handler executes.PostRequestHandlerExecute— after the handler executes.ReleaseRequestState— release of request state.UpdateRequestCache— update of the request cache.EndRequest— the end of request processing.Error— application-level error notification.
What Influence Can a Module Have?
A module can perform cross-cutting tasks such as authentication integration, logging, request inspection, security headers, timing measurements, and error handling.
Example
public class LoggingModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += (sender, args) =>
{
var context = ((HttpApplication)sender).Context;
System.Diagnostics.Trace.WriteLine(
context.Request.HttpMethod + " " +
context.Request.Url.AbsolutePath);
};
}
public void Dispose()
{
}
}
Can changes be made without recompiling the application?
Some changes can be made through configuration, such as registering an already compiled module, changing handler mappings, or updating settings in web.config, subject to the application's framework version and hosting configuration.
However, adding or changing the module's C# implementation generally requires compiling the module assembly. Updating application configuration may trigger an application restart.
16. Describe Ways to Present an Arbitrary Endpoint (URL) and Route Requests to That Endpoint to ASP.NET
Classic ASP.NET supports several ways to map a URL to application code.
- .aspx page: A Web Forms page handles the request and renders HTML.
- .ashx handler: A dedicated HTTP handler processes the request.
- IHttpHandler mapping: IIS or ASP.NET configuration maps a URL pattern or extension to a handler.
- IHttpModule: A module can observe and influence the request pipeline, although it is not itself the endpoint handler.
- ASP.NET routing: Maps URL patterns to route handlers, controllers, or other supported targets.
- URL rewriting: Transforms an incoming URL into another internal URL or route.
- Web services: ASMX services and other service endpoints expose functionality through configured URLs.
Example URL Patterns
/products.aspx?id=10
/CheckImage.ashx
/products/10
/api/products/10
The exact routing mechanism depends on the application framework and IIS configuration. ASP.NET Core uses endpoint routing and middleware rather than the classic Web Forms handler model.
17. Explain How Cookies Work. Give an Example of Cookie Abuse.
A cookie is a small piece of data that a website asks a browser to store. The browser can send the cookie back to the server in subsequent matching requests.
How Cookies Work
- The server sends a
Set-Cookieresponse header. - The browser stores the cookie according to its attributes.
- For a matching request, the browser sends the cookie in the
Cookierequest header. - The server reads the cookie to associate the request with relevant state or preferences.
Example
Response.Cookies["Theme"].Value = "Dark";
Response.Cookies["Theme"].HttpOnly = true;
Response.Cookies["Theme"].Secure = true;
This example sets a cookie for a theme preference. The Secure flag restricts transmission to HTTPS, and HttpOnly prevents ordinary JavaScript access to the cookie.
Cookie Abuse
One example is session hijacking, in which an attacker obtains a valid session cookie and attempts to impersonate its owner.
Other risks include:
- Cross-site scripting (XSS) that steals accessible cookies.
- Session fixation, where a victim is induced to use an attacker-known session identifier.
- Cross-site request forgery (CSRF) that abuses automatically submitted authentication cookies.
- Storing sensitive information in client-readable cookies without appropriate protection.
Prevention: Use HTTPS, secure cookie attributes, appropriate SameSite settings, session rotation after authentication, output encoding, and CSRF protections where applicable. Do not treat client-supplied cookie values as trustworthy without validation.
18. Explain the Importance of HttpRequest.ValidateInput()
In classic ASP.NET Framework, request validation is a security feature designed to detect certain potentially dangerous input, such as strings that resemble HTML or script markup, when request data is accessed.
The goal is to reduce the risk of unsafe input being processed as executable markup, particularly in applications vulnerable to cross-site scripting (XSS).
Important distinctions:
- Request validation is not a complete XSS defense.
- It does not replace context-appropriate output encoding.
- Applications that legitimately accept HTML need a carefully designed HTML sanitization strategy.
- Disabling request validation can expose unsafe assumptions in the application's input-handling logic.
In classic ASP.NET Framework, HttpRequest.ValidateInput() is associated with explicitly triggering validation of request collections. Request validation is normally integrated into the framework's request-processing behavior, so manual invocation is not required in every application.
Modern ASP.NET Core does not use the same built-in Web Forms request-validation model. Applications must validate inputs and encode outputs appropriately for their context.
19. What Kind of Data Is Passed via HTTP Headers?
HTTP headers carry metadata about a request or response. They describe how the message should be interpreted, authenticated, cached, or transmitted.
Common Request Headers
| Header | Purpose |
|---|---|
Host |
Identifies the target host name and, where applicable, port. |
User-Agent |
Provides information about the requesting client. |
Accept |
Describes response media types the client can accept. |
Authorization |
Carries authentication credentials or tokens. |
Cookie |
Sends applicable cookies to the server. |
If-Modified-Since |
Requests a conditional response based on a resource's modification time. |
Content-Type |
Describes the media type of the request body. |
Common Response Headers
Content-Type— the response media type.Cache-Control— caching directives.Set-Cookie— asks the browser to store cookies.Location— identifies a redirect target or another relevant resource location.Last-Modified— indicates when a resource was last modified.
Headers are separate from the message body, which may contain HTML, JSON, XML, form data, binary content, or other payloads.
20. Compare HTTP GET and POST. What Is HEAD?
| Feature | GET | POST | HEAD |
|---|---|---|---|
| Primary purpose | Retrieve a representation of a resource | Submit data for processing or resource creation | Retrieve response headers without the response body |
| Request body | Not generally used for request data | Commonly contains submitted data | Not generally used |
| Typical response | Resource representation | Depends on the operation | Headers corresponding to a GET response, without its body |
| Safe method | Yes, by HTTP semantics | No | Yes |
| Idempotent | Yes, by HTTP semantics | Not necessarily | Yes |
GET example:
GET /products?id=10 HTTP/1.1
POST example:
POST /products HTTP/1.1
Content-Type: application/json
{"name":"Laptop"}
HEAD example:
HEAD /products/10 HTTP/1.1
HEAD is useful when a client needs metadata, such as a resource's content type, modification date, or content length, without downloading the response body.
GET parameters may appear in URLs and can be recorded in browser history, logs, and referrer information. POST data is commonly sent in the request body, but POST is not automatically secure; HTTPS is needed to protect data in transit.
-----------------------------------------------------------------------------21. Name and Describe at Least Half a Dozen HTTP Status Codes
HTTP status codes tell the client how the server handled a request.
| Status code | Name | Meaning |
|---|---|---|
| 200 | OK | The request succeeded. |
| 201 | Created | The request successfully created a resource. |
| 204 | No Content | The request succeeded, and there is no response content. |
| 301 | Moved Permanently | The resource has a permanent redirect target. |
| 302 | Found | The resource is temporarily available at another location. |
| 304 | Not Modified | The client's cached representation can be reused under the applicable conditional request. |
| 400 | Bad Request | The server cannot process the request because it considers the request invalid. |
| 401 | Unauthorized | Valid authentication credentials are required or were not accepted. |
| 403 | Forbidden | The server refuses to fulfill the request. |
| 404 | Not Found | The requested resource was not found, or the server is unwilling to disclose its existence. |
| 405 | Method Not Allowed | The resource does not support the request method. |
| 409 | Conflict | The request conflicts with the current state of the resource. |
| 429 | Too Many Requests | The client has sent too many requests within a given period. |
| 500 | Internal Server Error | The server encountered an unexpected condition. |
| 502 | Bad Gateway | A gateway or proxy received an invalid response from an upstream server. |
| 503 | Service Unavailable | The server is temporarily unable to handle the request. |
Correct status codes help browsers, API clients, proxies, and caches determine how to handle a response.
22. How Does If-Not-Modified-Since Work? How Can It Be Implemented with ASP.NET?
The standard HTTP request header is If-Modified-Since. It lets a client ask whether a resource has changed since the supplied date.
How It Works
- The server sends a response containing a
Last-Modifiedheader. - The client caches the response and its modification date.
- On a later request, the client sends
If-Modified-Since. - If the resource has not changed since the supplied date, the server can respond with
304 Not Modifiedand no response body. - If the resource has changed, the server returns the updated representation, normally with a successful status such as
200 OK.
Classic ASP.NET Example
protected void Page_Load(object sender, EventArgs e)
{
DateTime lastModifiedUtc =
new DateTime(2026, 10, 20, 10, 0, 0, DateTimeKind.Utc);
Response.Cache.SetLastModified(lastModifiedUtc);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetMaxAge(TimeSpan.FromHours(1));
}
ASP.NET can handle standard conditional requests when the relevant response-cache settings and validators are configured. For application-specific resources, you may need to compare the incoming conditional header against the actual resource modification date and return the appropriate response.
Important: HTTP dates have one-second precision. If modification timestamps are compared manually, normalize the timestamps to UTC and account for this precision. Also consider the If-None-Match and ETag mechanism, which can provide more precise validation.
23. Explain <%@ OutputCache %> and the Usage of VaryByParam and VaryByHeader
The ASP.NET Web Forms @ OutputCache directive enables output caching for a page or user control. Instead of regenerating the page for every matching request, ASP.NET can reuse a cached response.
Basic Example
<%@ OutputCache Duration="60"
VaryByParam="none" %>
This caches the page output for up to 60 seconds under the applicable cache configuration, without creating separate variants for query-string or form parameters.
VaryByParam
VaryByParam determines which request parameters create separate cached page versions.
<%@ OutputCache Duration="60"
VaryByParam="q" %>
Requests with different values of q can have separate cache entries.
For example:
/page.aspx?q=1— one cache variant./page.aspx?q=2— another cache variant./page.aspx?q=5— another cache variant.
Use VaryByParam="*" when all applicable query-string and form parameters should participate in cache variation. Use VaryByParam="none" when parameter values should not create separate variants.
VaryByHeader
VaryByHeader creates separate cached responses based on the specified HTTP request headers.
<%@ OutputCache Duration="60"
VaryByParam="none"
VaryByHeader="Accept-Language" %>
For example, a page that renders different content based on Accept-Language can have separate cached variants for different language preferences.
Important: Cache only responses that can safely be reused for the requests sharing a cache key. Incorrect cache variation can expose user-specific content or return the wrong representation.
24. How Does VaryByCustom Work?
VaryByCustom lets an ASP.NET Framework application define custom rules for creating separate output-cache variants. The application implements those rules in the GetVaryByCustomString() method of its Global.asax application class.
Example Directive
<%@ OutputCache Duration="60"
VaryByParam="none"
VaryByCustom="browser" %>
The framework recognizes the special value browser for browser-based variation. For custom values, implement the corresponding method.
Custom Implementation
public override string GetVaryByCustomString(
HttpContext context,
string custom)
{
if (custom == "language")
{
return context.Request.UserLanguages != null
? context.Request.UserLanguages[0]
: "default";
}
return base.GetVaryByCustomString(context, custom);
}
A page can then use:
<%@ OutputCache Duration="60"
VaryByParam="none"
VaryByCustom="language" %>
The returned string determines the custom cache variation. Requests returning the same value can share a cache variant when the other cache-key conditions match.
Important: Custom variation must include every factor that changes the output. If the page depends on a user's identity or permissions, shared output caching requires particular care to avoid serving one user's content to another.
25. How Would You Implement ASP.NET HTML Output Caching for All Values of q Except q=5?
Suppose the URL is:
http://localhost/page.aspx?q=5
The requirement is to cache generated HTML for requests with different values of q, except requests where q=5.
A simple approach is to configure output caching programmatically, vary the cache by q, and explicitly prevent server caching for the excluded value.
Example: ASP.NET Web Forms
protected void Page_Load(object sender, EventArgs e)
{
string q = Request.QueryString["q"];
if (string.Equals(q, "5", StringComparison.Ordinal))
{
// Do not store this response in the ASP.NET server cache.
Response.Cache.SetNoServerCaching();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
else
{
// Allow server-side caching and vary by q.
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetMaxAge(TimeSpan.FromMinutes(1));
Response.Cache.VaryByParams["q"] = true;
}
}
How It Works
- When
q=5, the response is marked so it should not be stored in the server output cache or ordinary client caches. - For other values, server caching is enabled with a one-minute freshness period.
VaryByParams["q"] = trueensures that different values ofqcan have different server-cache entries.
Important implementation detail: Avoid adding an unconditional page-level @ OutputCache directive that independently caches the excluded response. For this conditional requirement, programmatic cache policy is easier to control. Verify behavior against the specific ASP.NET Framework version and hosting configuration.
Also, this example uses server-only caching for eligible responses. If a reverse proxy, CDN, or browser cache is involved, configure its caching policy separately and ensure it respects the intended exclusion.
Quick Revision Summary
| Topic | Key takeaway |
|---|---|
| In-Proc / Out-of-Proc | Same process versus separate process communication. |
| .NET IPC | Legacy .NET Remoting and COM/DCOM; modern alternatives include HTTP APIs, gRPC, and named pipes. |
| ASP.NET worker process | Historically aspnet_wp.exe on IIS 5.x and w3wp.exe on IIS 6.0 worker-process isolation. |
| Debug / Trace | Development diagnostics versus configurable tracing. |
| Form POST / PostBack | A submitted request is processed through the Web Forms lifecycle and can raise server-side events. |
| ViewState | Preserves Web Forms page/control state across postbacks; Base64 is encoding, not encryption. |
| machineKey | Protects ViewState and Forms Authentication data in classic ASP.NET Framework. |
| Session providers | InProc, StateServer, and SQLServer. |
| Web Gardening | Multiple worker processes on one server; each maintains separate in-memory state. |
| Thread reuse | ASP.NET uses reusable worker threads; a physical thread is not a permanent request identity. |
| ThreadStatic | Stores values per physical thread, not per web request. |
| HttpHandler | Handles specialized endpoints without the full Web Forms page lifecycle. |
| HttpModule | Observes and influences events across the request pipeline. |
| Cookies | Client-stored values sent back with matching requests; protect session identifiers. |
| Request validation | Helps detect potentially dangerous input but does not replace output encoding. |
| HTTP headers | Carry request/response metadata, authentication information, and caching directives. |
| GET / POST / HEAD | Retrieve a representation, submit/process data, and retrieve headers without a response body. |
| HTTP status codes | Communicate success, redirection, client errors, and server errors. |
| Conditional requests | If-Modified-Since and Last-Modified can reduce unnecessary response-body transfers. |
| OutputCache | Reuses generated HTML; VaryByParam and VaryByHeader control cache variation. |
| VaryByCustom | Implements application-defined cache variation. |
| Conditional output caching | Use a programmatic cache policy to exclude a specific query parameter value. |
| ASP.NET Interview Questions-1 to 10 :👈 | 👉:ASP-NET Interview Questions-21 to 30 |