Ultimate Classic ASP.NET Interview Guide 2026
220+ Q&A with business scenarios, AI integration & hands‑on code – Beginner to Architect
🔰 Beginner Level (0‑2 years) – 60 Questions
1. What is ASP.NET and how does it differ from ASP.NET Core?
Classic ASP.NET runs on the full .NET Framework and is tightly coupled to IIS and the System.Web assembly. It’s Windows‑only. ASP.NET Core is cross‑platform, modular, and no longer depends on System.Web.
2. Explain the architecture of ASP.NET (Web Forms, MVC, Web API).
Web Forms uses server controls and event‑driven model. MVC separates Model‑View‑Controller. Web API is for RESTful HTTP services. All share the same pipeline (HttpApplication, HttpModules, HttpHandlers).
3. What is the page lifecycle in Web Forms? List the events in order.
PreInit → Init → InitComplete → PreLoad → Load → Control events → LoadComplete → PreRender → SaveStateComplete → Render → Unload.
4. What are server controls? Give three examples and their HTML equivalents.
Server controls are ASP.NET components that render HTML and maintain state. E.g., <asp:TextBox> → <input type="text">, <asp:Button> → <input type="submit">, <asp:GridView> → <table>.
5. How is ViewState maintained in Web Forms? When should you disable it?
ViewState is a hidden field storing control state, encrypted and sent to client. Disable it when not needed to reduce page size and improve performance using EnableViewState="false".
6. What are the three ways to manage state in ASP.NET?
Client‑side: ViewState, cookies, QueryString, hidden fields. Server‑side: Session, Application, Cache.
7. Explain the difference between HttpContext.Current.Session and Application state.
Session is per‑user, stored either in‑proc or out‑of‑proc. Application is shared across all users and sessions.
8. How do you read a configuration value from web.config?
Use ConfigurationManager.AppSettings["key"] or for connection strings: ConfigurationManager.ConnectionStrings["name"].ConnectionString.
9. What is the purpose of the Global.asax file?
Handles application‑level events like Application_Start, Application_Error, Session_Start, and can register routes, filters.
10. How do you implement simple authentication using Forms Authentication in ASP.NET?
Configure <authentication mode="Forms"> in web.config, use FormsAuthentication.SetAuthCookie after validating credentials, and restrict pages with <authorization>.
11. What is the difference between Server.Transfer and Response.Redirect?
Server.Transfer changes execution on the server without a round‑trip; URL stays same. Response.Redirect sends a 302 to the browser causing a new request.
12. How do you handle unhandled exceptions in an ASP.NET Web Forms application?
Use Application_Error in Global.asax to log the error and redirect to a custom error page. Also use <customErrors> in web.config.
13. What are HTTP modules and HTTP handlers?
HTTP modules intercept requests and responses (like middleware). HTTP handlers process requests for specific file types (e.g., .aspx).
14. Write a simple HTTP handler that returns “Hello World” as plain text.
public class HelloHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable => false;
}
15. Explain the MVC pattern in ASP.NET MVC 5.
Model represents data, View displays data, Controller handles input and coordinates. Routing maps URLs to Controller actions.
16. How do you define a route in ASP.NET MVC?
In RouteConfig.cs: routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
17. What is the difference between ViewBag, ViewData, and TempData in MVC?
ViewBag is dynamic, ViewData is a dictionary, both live for current request. TempData survives across requests (uses Session).
18. How do you pass a model to a view in ASP.NET MVC?
In the controller action: return View(model); and in the view declare @model MyNamespace.MyModel.
19. What is the role of the ActionResult return type?
It’s the base class for all action results, allowing you to return different types: ViewResult, JsonResult, RedirectResult, etc.
20. How do you perform model validation using Data Annotations in MVC?
Decorate model properties with [Required], [StringLength], etc. In the controller, check ModelState.IsValid.
21. What are HTML helpers? Give three examples.
Methods that generate HTML: Html.TextBoxFor(), Html.ActionLink(), Html.BeginForm(). They support model binding and validation.
22. How do you implement a partial view and when would you use it?
Partial views are reusable view snippets. Use Html.Partial("_MyPartial") or Html.RenderPartial. Useful for widgets, lists that appear on multiple pages.
23. What is the difference between Razor and ASPX view engines?
Razor uses @ syntax, cleaner and less verbose. ASPX uses <%: %> and is similar to classic ASP. Razor is the default in MVC 3+.
24. How do you enable attribute routing in ASP.NET MVC 5?
In RouteConfig.cs, add routes.MapMvcAttributeRoutes(); and decorate actions with [Route("products/{id}")].
25. What is ASP.NET Web API and how does it differ from WCF?
Web API is a framework for building HTTP RESTful services. It’s lighter than WCF, uses content negotiation, and works well with JSON/XML.
26. How do you create a simple Web API controller that returns JSON?
public class ProductsController : ApiController {
public IHttpActionResult Get() {
var list = new List<string> { "Laptop", "Mouse" };
return Ok(list);
}
}
27. What is the difference between IHttpActionResult and HttpResponseMessage in Web API?
IHttpActionResult is a higher‑level abstraction introduced in Web API 2, simplifying response creation. HttpResponseMessage offers fine‑grained control.
28. How does routing work in Web API?
Default route: api/{controller}/{id}. Attribute routing can be enabled with config.MapHttpAttributeRoutes();.
29. Explain content negotiation in Web API.
The framework selects the formatter (JSON, XML) based on the Accept header from the client. You can customize formatters.
30. How do you secure a Web API using token‑based authentication?
Implement a custom DelegatingHandler that validates a token from the Authorization header. Or use OWIN middleware with JWT.
31. What is the purpose of the web.config file in ASP.NET?
It stores configuration settings like connection strings, app settings, authentication, HTTP modules, and custom error pages.
32. How do you handle file uploads in ASP.NET Web Forms?
Use the FileUpload server control. In code‑behind, check FileUpload1.HasFile and save with FileUpload1.SaveAs(Server.MapPath(...)).
33. What are master pages and how do they work?
Master pages define a common layout with ContentPlaceHolder controls. Content pages fill those placeholders. Helps maintain consistent UI.
34. Explain the difference between Server.UrlEncode and HttpUtility.UrlEncode.
Both encode URLs. Server.UrlEncode is specific to ASP.NET and uses UTF‑8. HttpUtility.UrlEncode is from System.Web and offers more overloads.
35. How do you implement caching in ASP.NET?
Use the Cache object: HttpRuntime.Cache.Insert("key", data, null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);.
36. What is the difference between output caching and data caching?
Output caching caches entire rendered pages/controls via <%@ OutputCache %> directive. Data caching stores arbitrary objects in the Cache object.
37. How do you read a query string in ASP.NET?
Use Request.QueryString["param"] in both Web Forms and MVC (via Request property).
38. What is the purpose of the IsPostBack property in Web Forms?
It indicates whether the page is being loaded in response to a postback. Used to avoid re‑binding data on every post.
39. How do you set a custom error page in ASP.NET?
In web.config: <customErrors mode="On" defaultRedirect="Error.aspx">. Also can add specific error status codes.
40. Explain the concept of "code‑behind" in Web Forms.
Code‑behind is the C#/VB file associated with an .aspx page, containing the page class and event handlers, separating logic from markup.
41. How do you use the Repeater control to display a list of items?
Bind a data source to the Repeater and define templates like ItemTemplate, HeaderTemplate. It renders custom HTML without a built‑in table structure.
42. What is a GridView and how do you handle the RowCommand event?
GridView displays tabular data. To handle button clicks, use OnRowCommand and check e.CommandName in code‑behind.
43. How do you enable session state and what are the session state modes?
Enabled by default. Modes: InProc (in‑memory, fast but not web‑farm friendly), StateServer, SQLServer, Custom.
44. What is the difference between Application_Start and Session_Start events?
Application_Start fires once when the application starts. Session_Start fires for each new user session.
45. How do you implement a simple contact form in Web Forms that sends an email?
Use System.Net.Mail.SmtpClient in the button click event. Ensure SMTP settings are configured in web.config.
46. What is Entity Framework (EF) and how is it used in classic ASP.NET MVC?
EF is an ORM. Use the DbContext class to query and save data. In MVC, instantiate the context in the controller and pass data to views.
47. How do you create a basic CRUD controller using Entity Framework in MVC?
Scaffold a controller with views using Entity Framework. It generates actions like Index, Create, Edit, Delete using the DbContext.
48. What is the difference between lazy loading and eager loading in EF?
Lazy loading loads related data when accessed (needs virtual navigation properties). Eager loading uses Include() to load upfront.
49. How do you handle concurrency in Entity Framework?
Add a RowVersion column (byte[] with [Timestamp]), catch DbUpdateConcurrencyException and resolve.
50. What are filters in ASP.NET MVC? Name the four types.
Filters are attributes that add pre/post processing: Authorization, Action, Result, Exception filters.
51. Write a custom action filter that logs action execution time in MVC.
public class TimerFilter : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
filterContext.HttpContext.Items["Start"] = DateTime.Now;
}
public override void OnActionExecuted(ActionExecutedContext filterContext) {
var start = (DateTime)filterContext.HttpContext.Items["Start"];
System.Diagnostics.Debug.WriteLine($"Duration: {(DateTime.Now - start).TotalMilliseconds}ms");
}
}
52. How do you enable bundling and minification in ASP.NET MVC?
Install Microsoft.AspNet.Web.Optimization. In BundleConfig.cs, define bundles. In view, use @Styles.Render("~/bundles/css").
53. What is the difference between JsonResult and Json method in MVC?
Json(data) is a controller method returning a JsonResult with default settings. JsonResult allows setting MaxJsonLength etc.
54. How do you call a Web API from an MVC controller using HttpClient?
Instantiate HttpClient, call GetAsync / PostAsync. Read content with ReadAsAsync<T> (or JsonConvert). Use using block or static instance.
55. What is Cross‑Site Request Forgery (CSRF) and how do you prevent it in MVC?
Use @Html.AntiForgeryToken() in forms and [ValidateAntiForgeryToken] on the controller action.
56. Explain how to host ASP.NET applications on IIS.
Create an IIS website, point to the application folder, assign an Application Pool with the correct .NET CLR version, and set permissions.
57. What is the role of the Global.asax in registering routes and filters?
In MVC, Application_Start calls RouteConfig.RegisterRoutes and FilterConfig.RegisterGlobalFilters.
58. How do you handle a large file upload without consuming too much server memory?
Use HttpRequest.GetBufferlessInputStream() and stream to disk in chunks. Set maxRequestLength in web.config.
59. What is the difference between Server.Execute and Server.Transfer?
Execute runs another page and returns to the original; Transfer stops original and runs new page. Both are server‑side.
60. How do you use the Membership and Roles providers in ASP.NET?
Configure in web.config. Use Membership.ValidateUser, Roles.IsUserInRole. Now largely replaced by ASP.NET Identity, but still asked.
🟡 Intermediate Level (2‑5 years) – 60 Questions
61. Design a high‑traffic product listing page in ASP.NET Web Forms with caching and paging.
Use output caching (VaryByParam) for the product list, implement custom paging with ObjectDataSource and stored procedures that only return the required page.
62. How would you implement role‑based authorization in an MVC intranet application?
Use Windows Authentication. Add [Authorize(Roles = "Domain\\Group")] on controllers/actions. Configure in web.config.
63. Explain the request pipeline in ASP.NET (classic). What events does an HTTP request go through?
Request → IIS → Application domain → HttpApplication events (BeginRequest, AuthenticateRequest, AuthorizeRequest, etc.) → HttpModule → HttpHandler → Response.
64. How do you create a custom HTTP module for logging request details?
Implement IHttpModule, subscribe to BeginRequest. Register in web.config <modules> section.
65. What is the difference between a synchronous and asynchronous HTTP handler?
Sync handler (IHttpHandler) blocks the thread during processing. Async handler (IHttpAsyncHandler) frees the thread, improving scalability.
66. Write an async Web API action using async/await.
public async Task<IHttpActionResult> Get() {
var data = await _service.GetProductsAsync();
return Ok(data);
}
67. How would you implement a custom model binder for a complex type in MVC?
Implement IModelBinder and register in ModelBinders.Binders.Add(typeof(MyType), new MyBinder());.
68. What is a dependency injection (DI) in classic ASP.NET? How do you set it up?
ASP.NET MVC doesn’t have built‑in DI. Use a third‑party container (Autofac, Unity). Integrate with a custom DependencyResolver.
69. How do you implement the Unit of Work pattern with Entity Framework in ASP.NET MVC?
Create a UnitOfWork class that wraps the DbContext and repositories. Dispose the UoW after the request (using DI per‑request scope).
70. Explain the Repository pattern and its benefits in an ASP.NET MVC application.
Repository abstracts data access, making the controller testable and data source swappable. Usually combined with Unit of Work.
71. How would you handle a long‑running process in an ASP.NET Web Forms page without timing out?
Use an async page with PageAsyncTask or move the process to a background job (e.g., Windows Service, Hangfire) and poll for status.
72. What are the best practices for error handling in Web API?
Use exception filters, global exception handler (GlobalConfiguration.Configuration.Filters), and return consistent error response objects (HttpError).
73. How do you implement versioning in ASP.NET Web API?
Via URL (/api/v1/products), query string (?version=1), or custom header. Often use a custom IHttpControllerSelector.
74. What is CORS and how do you enable it in Web API 2?
Install Microsoft.AspNet.WebApi.Cors, enable with config.EnableCors() and use [EnableCors] attribute on controllers.
75. How do you compress HTTP responses in ASP.NET?
Enable dynamic compression in IIS, or create a custom HTTP module that compresses the response stream based on Accept‑Encoding.
76. Design a modular architecture using Areas in ASP.NET MVC.
Areas separate large apps into sections (e.g., Admin, Blog). Each has its own controllers, views, and route registration. Register in AreaRegistration.RegisterAllAreas.
77. How would you secure an ASP.NET application against SQL injection?
Always use parameterized queries or an ORM (Entity Framework). Never concatenate user input into SQL. Validate and sanitize inputs.
78. Explain the concept of "thin controllers, fat models" and how to achieve it.
Move business logic to service classes, repositories, or domain models. Controllers only coordinate between HTTP and business layer.
79. How do you test an MVC controller with unit tests?
Mock dependencies using Moq. Verify action result type and model data. Use TestControllerBuilder to set up context.
80. What is the difference between System.Web.HttpContext.Current and HttpContextBase?
HttpContext.Current is static and hard to mock. HttpContextBase is an abstract class that can be mocked for unit testing.
81. How do you implement a custom membership provider in ASP.NET?
Inherit from MembershipProvider, override methods like ValidateUser, CreateUser. Configure in web.config.
82. How would you handle session state in a web farm environment?
Use out‑of‑proc session state: State Server or SQL Server. Ensure serializable objects, and configure the same machineKey across servers.
83. Explain the role of the machineKey in ASP.NET.
It is used to encrypt/decrypt ViewState, forms authentication tickets, and session state. Must be identical across web farm nodes.
84. How do you optimize a slow‑loading ASP.NET Web Forms page?
Enable ViewState for only needed controls, use output caching, minify CSS/JS, enable compression, use async page tasks, and optimize database queries.
85. What is the difference between Web Garden and Web Farm?
Web garden: multiple worker processes on same server. Web farm: multiple servers. Both require out‑of‑proc state management.
86. How would you implement a custom route constraint in MVC?
Implement IRouteConstraint with Match method. Use in route definition: new { id = new MyConstraint() }.
87. What are the different ways to pass data from controller to view?
Strongly‑typed model, ViewBag, ViewData, TempData, and sessions.
88. How do you use async and await in ASP.NET Web Forms 4.5+?
Set <%@ Page Async="true" %>. Use RegisterAsyncTask in Page_Load or use async void event handlers with caution.
89. Explain the concept of the "Pipeline" in ASP.NET Web API.
Web API has its own pipeline: HttpServer → DelegatingHandler chain → HttpControllerDispatcher → Controller. Handlers are analogous to OWIN middleware.
90. How do you create a custom DelegatingHandler to add a correlation ID to every response?
Override SendAsync, add X-Correlation-ID header. Register in GlobalConfiguration.Configuration.MessageHandlers.
91. What is OWIN and how does it relate to ASP.NET?
OWIN decouples web applications from the server. ASP.NET can use OWIN middleware (e.g., for OAuth, Katana) in the pipeline.
92. How do you implement Facebook/Google OAuth login in an ASP.NET MVC application?
Use OWIN middleware: app.UseFacebookAuthentication with app ID/secret. Or manually implement OAuth flow.
93. What are the benefits of using a DI container like Autofac in classic ASP.NET?
Loose coupling, testability, centralised lifetime management. Autofac integrates well with MVC/Web API.
94. How do you handle concurrent requests that update the same record in ASP.NET?
Use optimistic concurrency with a version column, or pessimistic locking via WITH (UPDLOCK) in a stored procedure.
95. What is the difference between HttpContext.Current.Items and Session?
Items holds data only for the current request, while Session persists across requests for the same user.
96. How would you implement a "remember me" functionality in forms authentication?
Pass true for createPersistentCookie in SetAuthCookie, and set a long expiration in web.config.
97. How do you configure Web API to return JSON by default?
Remove the XML formatter: config.Formatters.Remove(config.Formatters.XmlFormatter); or set JsonMediaTypeFormatter first.
98. What are the potential memory leaks in an ASP.NET application and how do you prevent them?
Unsubscribed event handlers, static collections growing indefinitely, not disposing DbContext. Use `using` blocks and profile with memory profiler.
99. How would you build a RESTful API that supports searching, filtering, and sorting?
Use OData query options ([EnableQuery]) or pass query parameters and build dynamic LINQ queries.
100. What is the purpose of the PreApplicationStartMethod attribute?
It allows code to run before application start, often used to register assemblies or modules without touching web.config.
101. How do you implement a single‑page application (SPA) using ASP.NET MVC and Knockout.js?
MVC serves the shell page, while Knockout.js on the client handles data binding. Web API provides JSON data. No full page reloads.
102. What is the difference between TempData.Keep and TempData.Peek?
Peek reads the value without marking it for deletion. Keep marks the whole TempData dictionary to be retained for the next request.
103. How do you implement a custom View Engine in ASP.NET MVC?
Inherit from VirtualPathProviderViewEngine and implement CreateView/CreatePartialView. Register in ViewEngines.Engines.
104. What are the common performance counters to monitor for an ASP.NET application?
Requests/Sec, Requests Executing, Errors Total, pipeline instance count, memory usage, thread pool usage.
105. How do you implement a CAPTCHA in an ASP.NET Web Forms page?
Use a custom HTTP handler to generate the image, store the text in session, and validate on postback.
106. Explain the difference between VirtualPathProvider and physical file system.
VirtualPathProvider abstracts file access, allowing you to serve views from embedded resources, databases, etc.
107. How do you handle globalization and localization in ASP.NET MVC?
Use resource files (.resx) and Thread.CurrentThread.CurrentCulture. Set culture based on user preference or cookie.
108. What is the difference between an HTTP module and an OWIN middleware?
HTTP module is IIS‑integrated; OWIN middleware is server‑agnostic. OWIN offers a more modern, decoupled pipeline.
109. How would you implement a throttling mechanism in Web API?
Create a DelegatingHandler or action filter that checks request count per client/IP and returns 429 if exceeded.
110. What is the role of IHttpControllerActivator in Web API?
It creates controller instances, enabling custom dependency injection or constructor parameterization.
111. How do you implement a custom AuthorizeAttribute in MVC/Web API?
Override AuthorizeCore or OnAuthorization. Add custom logic to verify user claims.
112. How would you deploy an ASP.NET application with zero downtime?
Use a load balancer with multiple servers. Take one server out of rotation, update, and bring back. Or use deployment slots in Azure App Service (classic).
113. What is the purpose of the PreSendRequestHeaders and PreSendRequestContent events?
They fire just before the response headers/content are sent. Rarely used; can be used to modify output at the last moment.
114. How do you use async with RegisterAsyncTask in Web Forms?
protected void Page_Load(object sender, EventArgs e) {
RegisterAsyncTask(new PageAsyncTask(async cancellationToken => {
var data = await GetDataAsync();
// Bind data
}));
}
115. What is the difference between Response.Write and Response.Output.Write?
Response.Write outputs unformatted string. Response.Output.Write uses a TextWriter that supports format strings.
116. How do you protect against cross‑site scripting (XSS) in ASP.NET?
By default, ASP.NET validates input for dangerous characters (ValidateRequest). Output encode data with HttpUtility.HtmlEncode or use <%: %> in Razor.
117. What is the ViewStateUserKey property?
It ties ViewState to a specific user (e.g., Session ID), preventing one‑click attacks. Set it in Page_Init.
118. How do you implement a custom session state store?
Inherit from SessionStateStoreProviderBase, override methods, and configure in web.config.
119. How would you integrate ASP.NET Web Forms with an AngularJS front‑end?
Use Web Forms to serve the shell page and bundle scripts. Backend data provided through Web API or Page Methods. Angular handles UI logic.
120. What is the impact of EnableViewStateMac and how does it enhance security?
It adds a hash to ViewState to detect tampering. Should always be enabled unless there’s a very good reason.
🔴 Expert Level (5‑10 years) – 60 Questions
121. Design a multi‑tenant architecture in classic ASP.NET MVC with shared database and tenant isolation.
Use a TenantContext resolved from the host header or subdomain. Add a global filter that sets a tenant ID on the thread. All queries are filtered by tenant ID.
122. How would you implement the command and query segregation (CQRS) pattern in ASP.NET Web API?
Separate command and query services. Use MediatR with DI container. Commands update data, queries read from a denormalized view or separate read‑model database.
123. Explain the use of async/await in a legacy Web Forms application and the pitfalls.
Must set Async="true" and use RegisterAsyncTask properly. Avoid async void event handlers. Ensure HttpContext is captured correctly.
124. How do you implement a custom VirtualPathProvider to serve views from a database?
Override FileExists and GetFile, return a VirtualFile that reads content from the database. Register in Application_Start.
125. What is the best strategy to migrate a large Web Forms application to MVC incrementally?
Use a hybrid approach: add MVC to the existing project, route new features to MVC controllers, slowly rewrite Web Forms pages. Use URL routing to keep old URLs working.
126. How do you use SignalR in an ASP.NET MVC application for real‑time updates?
Install Microsoft.AspNet.SignalR. Map hubs in OWIN startup. Clients can connect to the hub, server pushes updates. Still classic ASP.NET compatible.
127. What are the challenges of using Entity Framework in a high‑throughput classic ASP.NET app?
Context lifetime management (per‑request), N+1 queries, change tracking overhead. Solution: use short‑lived contexts, AsNoTracking for reads, and compiled queries.
128. How do you implement a distributed cache (Redis) in an ASP.NET Web Forms app?
Use StackExchange.Redis client in a service layer. Replace HttpRuntime.Cache with Redis for shared state across servers.
129. Design a reliable email sending service that integrates with ASP.NET MVC using a message queue.
MVC action enqueues a message (Azure Service Bus / RabbitMQ). A background Windows service or Azure WebJob consumes the queue and sends emails. Use Outbox pattern for reliability.
130. How would you build an API gateway using classic ASP.NET Web API that routes to downstream services?
Create a controller that acts as a reverse proxy using HttpClient. Add authentication, logging, and rate limiting. Can use DelegatingHandler pipeline.
131. What are the best practices for error logging and monitoring in a classic ASP.NET production application?
Use ELMAH, Log4net, or Serilog. Log to a centralized store (ELK). Implement Application_Error to catch unhandled exceptions. Use Application Insights SDK.
132. How do you secure a classic ASP.NET application using HTTPS and HSTS?
Enforce HTTPS by redirecting HTTP to HTTPS (URL rewrite or custom module). Add Strict-Transport-Security header via custom header in web.config or code.
133. Explain the concept of "ambient context" and its use in ASP.NET (e.g., HttpContext.Current). How to make it testable?
Abstract HttpContext behind an IHttpContextProvider interface and inject it. Use HttpContextBase for mocking.
134. How would you implement a custom output cache provider in ASP.NET (e.g., using Redis)?
Inherit from OutputCacheProvider, override Add, Get, Set, and register in web.config.
135. What are the differences between IIS integrated pipeline and classic mode?
Integrated mode unifies ASP.NET and IIS pipeline, allowing managed modules to process all requests. Classic mode keeps them separate (for backward compatibility).
136. How do you implement request throttling using an HTTP module that reads rules from a database?
Create an IHttpModule that in BeginRequest checks client IP/token against limits stored in cache (refreshed periodically from DB), and returns 429.
137. Design a scalable image resizing service using an ASP.NET HTTP handler.
Handler accepts image URL and size parameters, retrieves original from storage, resizes, caches to disk/CDN, and streams back. Use asynchronous handler for scalability.
138. How do you use Application Insights in a classic ASP.NET app to track dependencies and exceptions?
Install Microsoft.ApplicationInsights.Web NuGet package. It auto‑collects requests and exceptions. Add TelemetryClient to track custom events.
139. What is the "double hop" problem in authentication and how do you solve it in ASP.NET?
When the app needs to pass credentials to a back‑end service (e.g., SQL Server). Use Kerberos delegation or a trusted subsystem model (app pool identity).
140. How would you implement a custom UrlHelper extension to generate SEO‑friendly slugs?
Create extension methods on UrlHelper that format route values, appending a slug parameter derived from the title. Use attribute routing with optional slug.
141. How do you handle database migrations in a classic ASP.NET application using Entity Framework?
Enable migrations, use Update-Database from Package Manager Console. Or run DbMigrator in Application_Start for automatic migration.
142. What is the best way to share authentication between an ASP.NET MVC app and a Web API on different subdomains?
Use a shared machine key for cookie encryption and set the cookie domain to the parent domain (e.g., `.mydomain.com`).
143. How would you build a plugin‑based architecture in ASP.NET MVC using MEF or Autofac?
Define interfaces in a shared assembly. Plugins implement them. Use a DI container to scan assemblies and register implementations. Controllers can be discovered dynamically.
144. How do you implement A/B testing in a Web Forms application using a custom PageHandlerFactory?
Override the page factory to serve different page versions based on a cookie/random assignment. Track metrics via analytics.
145. What are the security implications of using ValidateRequest="false"?
Disables ASP.NET’s built‑in request validation, opening the door to XSS attacks. Must carefully encode all output.
146. How can you leverage the Windows Identity Foundation (WIF) in classic ASP.NET for claims‑based authentication?
Use WIF middleware to transform SAML tokens or JWT into claims, set up ClaimsPrincipal. Configure in web.config with SessionAuthenticationModule.
147. Design an API that supports both XML and JSON based on content negotiation in Web API, with custom formatters.
Use the default JSON/XML formatters. For custom types, create a MediaTypeFormatter and register it.
148. How do you implement a "circuit breaker" pattern in an ASP.NET MVC application calling an external AI service?
Wrap calls with Polly (available on .NET Framework). Use Policy.Handle<Exception>().CircuitBreakerAsync(...). Store circuit state in static or cache.
149. What is the role of System.Transactions in ASP.NET and how to use TransactionScope for distributed transactions?
Allows ambient transactions across multiple databases. Use with TransactionScopeAsyncFlowOption.Enabled for async. Be cautious of performance.
150. How would you migrate a classic ASP.NET app to Azure Cloud Services (classic) or App Service?
For App Service, deploy directly. Ensure connection strings use Azure SQL. For Cloud Services, add a web role project. Consider removing reliance on local file system.
151. How do you enable HTTP/2 in a classic ASP.NET application hosted on IIS?
HTTP/2 is automatically enabled on IIS 10+ with HTTPS. No code changes needed, but ASP.NET must use integrated pipeline.
152. What is the difference between HttpResponse.Close, HttpResponse.End, and HttpApplication.CompleteRequest?
End throws an exception to abort, Close closes the connection abruptly, CompleteRequest signals the pipeline to skip to the EndRequest event gracefully.
153. How do you implement a custom health check endpoint in Web API that verifies database connectivity?
Add a controller action that attempts a simple query (e.g., SELECT 1) and returns 200 if successful, 503 if not. Register a route like /health.
154. What are the steps to enable WebSocket support in an ASP.NET Web Forms application?
Use a custom IHttpHandler that accepts WebSocket requests (context.IsWebSocketRequest). Use AcceptWebSocketRequest and manage the socket. SignalR is a better alternative.
155. How would you build a custom SiteMapProvider that pulls navigation from a database?
Inherit from StaticSiteMapProvider, override BuildSiteMap to populate nodes from DB. Register in web.config.
156. How do you detect and prevent session fixation attacks in classic ASP.NET?
Regenerate the session ID after login using SessionIDManager.SaveSessionID or by abandoning the old session and starting a new one.
157. Explain the use of the aspnet_regiis.exe tool.
It registers ASP.NET with IIS, encrypts/decrypts configuration sections, and manages assembly caches.
158. How do you implement output caching that varies by user role in MVC?
Use VaryByCustom in [OutputCache] and override GetVaryByCustomString in Global.asax to return role string.
159. What are the benefits of using async controllers in ASP.NET MVC 4+?
Frees up IIS threads during I/O operations, improving scalability under high load.
160. How do you create a custom ActionInvoker in ASP.NET MVC?
Inherit from ControllerActionInvoker and override InvokeAction to add custom pre/post processing. Set controller's ActionInvoker property.
161. How would you implement a feature flag system in an ASP.NET Web Forms application?
Read flags from web.config or a database. Use a custom base page that checks flags and shows/hides controls accordingly.
162. What is the best way to handle large volume of file downloads with resume support in Web Forms?
Write an IHttpHandler that processes Range headers, sets appropriate response headers, and streams the file in chunks.
163. How do you use System.Threading.Tasks.Dataflow in an ASP.NET pipeline for parallel processing?
Create a dataflow mesh in a background task (e.g., using HostingEnvironment.QueueBackgroundWorkItem) to process queued items. Not common but possible.
164. How can you implement an API that supports bulk operations using multipart content?
Use MultipartFormDataStreamProvider in Web API to parse bulk upload of files and JSON data.
165. What is the purpose of HttpContext.RemapHandler?
Allows changing the handler during request processing. Useful in advanced scenarios like URL rewriting to a different handler.
166. How would you integrate a classic ASP.NET app with Azure Service Bus for reliable messaging?
Use Microsoft.Azure.ServiceBus client. In Global.asax start a message pump or use a background task. Use QueueBackgroundWorkItem for asynchronous processing.
167. Design a solution for real‑time inventory updates across multiple servers using SignalR and a Redis backplane.
Each server runs SignalR hub; use Redis backplane (SignalR scaleout) to broadcast messages to all clients regardless of which server they're connected to.
168. How do you handle ThreadAbortException when using Response.Redirect?
Use Response.Redirect(url, false) to avoid the exception, followed by HttpApplication.CompleteRequest.
169. What are the differences between HttpRuntime.Cache and System.Runtime.Caching.MemoryCache?
HttpRuntime.Cache is ASP.NET specific and tied to the application domain. MemoryCache is generic and can be used outside ASP.NET.
170. How would you implement a custom IHttpHandler that acts as a reverse proxy for legacy services?
Handler reads incoming request, creates a new HttpWebRequest to the legacy endpoint, copies headers, streams request body, and copies response back.
171. How do you use the HostingEnvironment.QueueBackgroundWorkItem for fire‑and‑forget tasks?
It schedules a background task that is tracked by ASP.NET and ensures the application domain stays alive until the task completes, preventing premature shutdown.
172. What are the implications of setting debug="true" in production?
It enables debug symbols, disables optimizations, causes memory leaks (due to GC behavior), and significantly degrades performance. Must be false in production.
173. How do you implement sliding expiration in a custom cache?
Track last access time. On retrieval, reset the cache entry with a new sliding expiration using Cache.Insert with Cache.NoSlidingExpiration to preserve pattern.
174. How can you use System.Diagnostics.Stopwatch to profile specific parts of an MVC request?
Use an action filter that starts a stopwatch in OnActionExecuting and logs in OnActionExecuted. Store in HttpContext.Items.
175. How would you implement a custom IControllerFactory in MVC for advanced DI scenarios?
Override CreateController and ReleaseController. Use DI container to resolve controller and its dependencies. Register in ControllerBuilder.Current.
176. What is the recommended way to set up an ASP.NET application for load testing?
Disable debug mode, enable output caching, set numProcesses appropriately, use a release build, and warm up the application.
177. How do you implement a custom VirtualFile that minifies JavaScript on the fly?
Inherit from VirtualFile, open the original file, minify content using e.g. NUglify, and return the minified stream. Use VirtualPathProvider to serve.
178. How would you integrate Azure Cognitive Services (e.g., Translator) into an ASP.NET Web Forms page?
Call the Cognitive Services REST API from code‑behind using HttpClient. Display translated text in labels. Secure API key in web.config.
179. What is the best practice for managing database connections in ASP.NET?
Open connections as late as possible, close them as soon as possible. Use using blocks or repository pattern with DbContext per request.
180. How do you implement a global action filter in MVC that adds a response header?
Create an ActionFilterAttribute and override OnActionExecuted to add header. Register in GlobalFilters.Filters.Add(...).
👑 Most Expert / Architect (10+ years) & AI‑Oriented – 40 Questions
181. How do you integrate an AI chatbot (like Azure OpenAI GPT‑4) into a classic ASP.NET MVC application?
Call the Azure OpenAI REST API from a service class using HttpClient. Keep API key in Azure Key Vault. Use async calls to avoid blocking. Stream responses using chunked transfer.
182. Design a classic ASP.NET Web API that uses ML.NET to serve a pre‑trained machine learning model for customer churn prediction.
Load the model in a static variable during startup. Create a controller action that maps input to model input class, calls PredictionEngine (pooled), and returns prediction.
183. How would you build a RAG (Retrieval‑Augmented Generation) application using classic ASP.NET and Azure Cognitive Search?
On document upload, generate embeddings using Azure OpenAI and store in Cognitive Search. For queries, embed user question, retrieve relevant chunks, then send to GPT for final answer. Use asynchronous handlers.
184. What are the challenges of using AI services from a classic ASP.NET app and how to address them?
Latency, blocking calls, and API key security. Solution: make all AI calls async, use caching for frequent queries, store secrets in Key Vault with Managed Identity if possible, and implement circuit breaker with Polly.
185. How do you implement a recommendation engine that updates periodically using a background job in classic ASP.NET?
Use a Windows Service or Azure WebJob that periodically retrains an ML.NET model and saves it. The web app reloads the model from blob storage.
186. How can you use AI to automatically moderate user comments in an ASP.NET Web Forms forum?
On postback, send comment text to Azure Content Moderator API. Based on the score, either flag for review or block posting.
187. What is the best approach to add AI‑powered search autocomplete to an ASP.NET MVC site?
Use Azure Cognitive Search's autocomplete feature. Controller action calls the search index as the user types (via AJAX) and returns suggestions.
188. How would you secure the communication between a classic ASP.NET app and an AI microservice hosted on Kubernetes?
Use HTTPS with mTLS or an API gateway. The ASP.NET app authenticates with a JWT or API key. All secrets stored securely.
189. Design a classic ASP.NET application that uses Azure Cognitive Services Vision API to analyze uploaded images.
After upload, call the Vision API with the image byte array. Process the JSON response (tags, description) and store in the database. Use async to avoid blocking the upload.
190. How do you implement an AI‑driven dynamic pricing feature in an e‑commerce ASP.NET MVC app?
Build an ML model that predicts price elasticity. The product page controller calls the model with user context and adjusts price. Model is updated periodically via background job.
191. What is the role of the Semantic Kernel SDK in classic ASP.NET? Can you use it?
Semantic Kernel can be used in .NET Framework 4.7.2+ apps. It orchestrates AI plugins and memory. You can add it to an ASP.NET MVC service to build AI workflows.
192. How do you monitor AI service calls in a classic ASP.NET app and track token usage per user?
Wrap AI calls with logging (using ILogger or custom). Track usage in a database table. Use Application Insights for telemetry.
193. How would you build a pluggable AI service layer in an ASP.NET MVC app that can switch between OpenAI and Azure AI?
Define an IAICompletionService interface. Implement for OpenAI and Azure. Register the appropriate implementation based on configuration (DI).
194. What are the ethical considerations when adding AI features to a classic ASP.NET public website?
Transparency (inform users AI is used), bias mitigation, data privacy (GDPR), and providing an opt‑out option.
195. How can you use AI to generate SEO‑friendly meta tags dynamically in an ASP.NET MVC e‑commerce site?
In the controller, fetch product description, send to GPT to generate title/description, cache the result, and output in the view.
196. Design a classic ASP.NET API that accepts a natural language query and converts it to SQL using AI (NL2SQL).
Send the user’s question along with database schema to GPT. Execute the generated SQL read‑only. Validate and sanitize the generated SQL carefully.
197. How do you implement an AI‑powered chatbot using Web API and Azure Bot Service with a classic ASP.NET frontend?
Host a bot using Microsoft Bot Framework SDK in a separate Web API. Classic ASP.NET frontend uses DirectLine JavaScript to communicate with the bot.
198. What is the impact of using AI on the scalability of a classic ASP.NET application?
AI calls add latency and cost. Mitigate by async processing, caching results, and using request queueing with a background worker.
199. How would you implement a feedback loop where users can correct AI predictions, improving the model over time?
Store user corrections with input data in a database. Periodically retrain the model using this new data. A/B test model versions.
200. How do you version an AI model endpoint in a classic ASP.NET Web API?
Include version in the URL or header. Use different controller routes to forward to different model deployments. Or use a configuration switch.
201. Design a system that uses AI to analyze customer support tickets and suggest solutions from a knowledge base.
Use Text Analytics API to extract key phrases. Search the knowledge base (SQL full‑text or Cognitive Search) for similar tickets. Return top matches with confidence scores.
202. How can you use Azure Form Recognizer in an ASP.NET MVC app to process invoices?
Uploaded invoice PDF is sent to Form Recognizer. The resulting fields are extracted and displayed in a view for user confirmation before saving to DB.
203. What are the best practices for prompt engineering when calling OpenAI from a classic ASP.NET service?
Use clear system instructions, separate user and assistant messages, provide few‑shot examples, set temperature low for deterministic responses, and validate output.
204. How do you handle rate limiting of AI APIs in a classic ASP.NET app to avoid throttling?
Implement retry with exponential backoff (Polly). Use a distributed cache (Redis) to track request count per minute. Queue requests if limit reached.
205. How would you implement a content safety filter for AI‑generated text before displaying to users?
Use Azure Content Safety API. After getting AI response, call the safety endpoint; if flagged as harmful, show a fallback message.
206. How do you set up continuous integration and deployment (CI/CD) for a classic ASP.NET app that includes an AI model?
Use Azure DevOps pipelines. Model is trained separately; the trained model is stored as an artifact and deployed alongside the app. Use web deploy or FTP.
207. What are the differences between using ML.NET and Azure Cognitive Services for an ASP.NET app?
ML.NET runs locally, no latency, no API cost, but requires model management. Cognitive Services are cloud‑based, scalable, and require network calls.
208. How would you implement a "smart" caching layer that uses AI to predict what data to pre‑fetch?
Analyze historical access patterns with ML.NET time series. Predict upcoming popular items and pre‑load them into cache via a background job.
209. Design an ASP.NET MVC action that uses AI to summarize a long article for a preview snippet.
Send article text to GPT with a summarization prompt. Cache the summary by article ID. Display on the listing page.
210. How do you integrate Azure Speech Services to enable voice commands in a classic ASP.NET web app?
Use the Speech SDK JavaScript on the client to capture audio. The audio is sent to the server (Web API) which uses the Speech Service to transcribe, then processes the command.
211. How would you build an AI‑assisted code review tool inside an ASP.NET MVC portal?
Submit code snippet to GPT with instructions to review. Display the review feedback in the view. Keep a history of reviews.
212. What are the performance considerations when calling an AI model with large payloads in a classic ASP.NET request?
Use streaming API to reduce memory footprint. Set appropriate timeouts. Process asynchronously and return status endpoint if needed.
213. How do you use Azure Key Vault to store AI API keys and retrieve them in classic ASP.NET?
Use Azure.Identity and Azure.Security.KeyVault.Secrets libraries. The application authenticates via Managed Identity or client secret. Load secrets in Application_Start and store in static variables.
214. How can you use AI to detect anomalies in web traffic for a classic ASP.NET site?
Stream IIS logs to Azure Monitor/Log Analytics, use built‑in anomaly detection. Or feed request data to Azure Anomaly Detector API and alert on high scores.
215. Design an AI‑powered personalization engine for an ASP.NET MVC product catalog.
Track user behavior. Use ML.NET recommendation to suggest products. Store user profile in session/database. Render recommendations via partial view.
216. What is the recommended way to handle long‑running AI tasks (e.g., video analysis) from a classic ASP.NET page?
Drop a message into a queue (Azure Storage Queue) and have a background worker (WebJob) process it. Page polls a status endpoint or uses SignalR for completion notification.
217. How do you ensure data privacy when sending user data to an external AI service from a classic ASP.NET app?
Anonymise PII before sending. Use on‑premise models if possible. Ensure your legal terms cover the usage.
218. How would you implement a "bring your own AI model" feature where tenants upload their own ML model?
Provide an upload interface. Validate the model format (ONNX). Load model in a separate AppDomain or process for isolation. Execute predictions with strict sandboxing.
219. How do you create a dashboard that shows AI prediction accuracy over time in a classic ASP.NET app?
Log predictions and actual outcomes. Use a charting library (e.g., Chart.js) to display accuracy trend. Data aggregated in SQL and exposed via Web API.
220. What does an AI‑first architecture look like for a classic ASP.NET application in 2026?
Every feature has an AI component: intelligent search, personalization, automation, content generation. AI services are treated as core dependencies, with robust monitoring, fallback, and ethical guidelines in place. Classic ASP.NET serves as a reliable shell, while AI microservices are consumed asynchronously.

0 Comments
thanks for your comments!