Land the job you want — prepare
with Real interviews Q&A
Curated interview questions, company-wise guides and coding rounds. Practice mock interviews, improve with feedback, and track your progress.
ASP.NET is a modern open-source web application framework created by Microsoft designed for compiling rich dynamic web solutions, RESTful API instances, and distributed microservice workloads using C# and .NET.
// Dynamic web API endpoint in ASP.NET Core (Minimal APIs)
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Welcome to ASP.NET Core API!");
app.Run();The ecosystem has evolved from classical legacy modules into highly consolidated, open-source frameworks:
// Architectural ecosystem framework selection
// 1. ASP.NET Web Forms (Legacy event-driven)
// 2. ASP.NET MVC (Structured separation)
// 3. ASP.NET Web API (RESTful endpoint interfaces)
// 4. ASP.NET Core (Modern, high performance, cross-platform)Web Forms is a legacy event-driven ASP.NET development paradigm centered on visual desktop-like drag-and-drop server controls. It automatically handles viewstates to manage UI rendering behaviors across page interactions.
<!-- ASP.NET Web Forms Event-Driven server side control markup -->
<asp:Button ID="btnSubmit" runat="server" Text="Click Me" OnClick="btnSubmit_Click" />ASP.NET MVC splits complex logic structures into three isolated modules: the Model (data payload rules), the View (HTML presentation templates), and the Controller (processing logic routing pipelines).
// Model-View-Controller design architecture pattern
public class HomeController : Controller {
public IActionResult Index() {
return View(); // Routes control flow directly to the layout view
}
}ASP.NET Core is the modern, cloud-optimized, cross-platform successor framework to traditional ASP.NET. It runs identically on Windows, Linux, and macOS environments, completely free of legacy IIS server hosting dependencies.
// Program entry startup bootstrapping in ASP.NET Core
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseStaticFiles();
app.UseRouting();
app.MapDefaultControllerRoute();
app.Run();Code-behind is a design pattern separating visual layout pages (.aspx) from server-side interaction files (.aspx.cs). It helps isolate presentation layouts from transactional back-end business logic.
// Code-behind mechanism: separation of layout and business processing logic
// Page.aspx markup binds to class code-behind file dynamically
public partial class UserDashboard : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
lblMessage.Text = "Welcome to Server Control logic!";
}
}ViewState is a system mechanism in classic Web Forms that retains control values across postback cycles. It serializes data states into a base64 string hidden inside HTML forms.
<!-- Hidden structural system state tracking payload inside generated browser DOM -->
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjg0Nzc0MD..." />A postback is the action of transmitting layout forms back to the host server for execution. Developers can check if the page is rendering for the first time or resolving a postback using the IsPostBack property.
// Handling user postbacks safely inside page transaction sequences
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
// Runs exclusively on the initial client landing request
PopulateDropdowns();
}
}Server Controls are server-side components in classic Web Forms that output HTML tags. They feature the runat="server" property, allowing them to be managed programmatically in code-behind files.
<!-- Server-side UI tag rendering elements inside dynamic engine compiler -->
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-input" Required="true" />A Master Page defines a shared layout template (containing header, sidebar, navigation, and footer structures) that is inherited dynamically across child content pages.
<!-- Master layout structure containing shared template content boxes -->
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.Master.cs" %>
<div class="header">Main Application Layout Header</div>
<asp:ContentPlaceHolder ID="MainBodyContent" runat="server">
<!-- Child page unique body elements are injected directly here -->
</asp:ContentPlaceHolder>web.config is an XML configuration file used in classic ASP.NET to manage database connections, authentication rules, security restrictions, and framework behaviors.
<!-- XML application-level settings configuration parameters inside web.config -->
<configuration>
<appSettings>
<add key="ApplicationMode" value="Production" />
</appSettings>
<connectionStrings>
<add name="DbConn" connectionString="Server=SQLServer;Database=MyDB;Trusted_Connection=True;" />
</connectionStrings>
</configuration>Global.asax is an application-level file used in classic ASP.NET to intercept lifecycle events, such as application startup, session initiation, and unhandled system errors.
// Application-level lifecycle events inside global.asax
public class Global : System.Web.HttpApplication {
protected void Application_Start(object sender, EventArgs e) {
// Runs on initial web app pool initiation sequences
RegisterRoutes(RouteTable.Routes);
}
}Session State retains user-specific data across multiple request steps. The state container runs as an in-memory dictionary, distributed SQL servers, or Redis cache backends.
// Saving user session state payload buffers across server steps
HttpContext.Session.SetString("UserEmail", "akash@example.com");
// Reading data dynamically from session storage buffers
var email = HttpContext.Session.GetString("UserEmail");Caching stores processed output data in high-performance memory buffers to serve future requests quickly without reprocessing logic or querying databases.
// Output caching strategy configurations on actions
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)]
public IActionResult GetCachedData() {
return Ok(new { Timestamp = DateTime.UtcNow });
}Authentication is the security process of verifying user identity credentials (e.g., matching database usernames and passwords or validating external OAuth access keys).
// Implementing cookie authentication configuration mechanisms
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
});Authorization validates security permissions to determine which restricted system resources, pages, or API endpoints an authenticated user is allowed to access.
// Managing user resource accessibility via role controls
[Authorize(Roles = "Admin, Manager")]
public class AdminController : Controller {
public IActionResult Dashboard() => View();
}Routing is the engine that maps incoming HTTP request URLs to the appropriate controller action methods, handling variable parameter extractions automatically.
// Mapping routing patterns dynamically in the startup configuration
app.MapControllerRoute(
name: "products",
pattern: "store/{category}/{id?}",
defaults: new { controller = "Products", action = "Details" });Dependency Injection (DI) is a design pattern used to decouple components. Instead of classes instantiating dependencies directly, the host container injects them at runtime.
// Registering and injecting constructor services via native DI containers
builder.Services.AddScoped<IUserRepository, UserRepository>();
public class UserController : Controller {
private readonly IUserRepository _repo;
public UserController(IUserRepository repo) {
_repo = repo; // Loose coupling architecture
}
}Middleware is software assembled into an application pipeline to handle requests and responses. Each component can inspect, redirect, block, or modify requests in transit.
// Dynamic pipeline middleware processing step delegates
app.Use(async (context, next) => {
// Process request operations prior to passing up pipeline
await next();
// Post-processing execution tasks before returning output
});Razor is a markup syntax used to embed C# code dynamically inside HTML views. It utilizes the @ prefix symbol to transition between markup and server-side code.
<!-- Structured Razor view layout programming loops -->
@model List<string>
<ul>
@foreach(var name in Model) {
<li class="user-item">User: @name</li>
}
</ul>A Partial View is a reusable layout block designed to render specific visual sub-modules within larger host view layouts, avoiding redundant UI markup.
<!-- Reusable isolated layout component injection -->
<div class="sidebar">
<partial name="_UserCard" model="Model.CurrentUser" />
</div>TempData is a dictionary container used to store temporary values that survive exactly one HTTP redirection step, automatically clearing itself after access.
// Temporary storage passing patterns surviving exactly one redirection step
public IActionResult UpdateSettings() {
TempData["AlertMessage"] = "System settings modified successfully!";
return RedirectToAction("Dashboard");
}ViewBag is a dynamic container property used to pass values from controllers to view templates. It utilizes dynamic properties that are validated only at runtime.
// Passing un-typed dynamic parameters cleanly from controller contexts down to views
public IActionResult Index() {
ViewBag.PageTitle = "System Administration Panel";
return View();
}Model Binding maps incoming HTTP query strings, route parameters, or JSON request bodies directly onto action parameters or strongly-typed object classes.
// Binding incoming query string payloads directly inside API methods
[HttpGet("search")]
public IActionResult FindProducts([FromQuery] string query, [FromQuery] int limit) {
return Ok($"Searching for: {query}, Limit: {limit}");
}ActionResult is the base class for controller action responses. It handles various HTTP response states, such as Ok() (200), NotFound() (404), or View() markup.
// Base controller return results managing REST protocols
public IActionResult GetSystemStatus(int id) {
if (id <= 0) return BadRequest("Invalid target ID specified.");
return Ok(new { Status = "Online", Code = 200 });
}Filters intercept controller action lifecycles. They permit running custom code blocks (e.g., performance logging, authorization checks, exception handlers) before or after execution.
// Building custom action filters handling horizontal security concerns
public class LogActionFilter : IActionFilter {
public void OnActionExecuting(ActionExecutingContext context) {
Console.WriteLine($"Initiating Action: {context.ActionDescriptor.DisplayName}");
}
public void OnActionExecuted(ActionExecutedContext context) {}
}Bundling combines multiple CSS or JS files into a single bundle to reduce browser requests, while Minification compresses code size by removing whitespace and comments.
// Bundle dynamic assets to reduce browser HTTP handshake limits
// ScriptBundle consolidates files while minimizing Whitespace and Comments
var scriptBundle = new ScriptBundle("~/bundles/corejs")
.Include("~/Scripts/jquery-{version}.js", "~/Scripts/bootstrap.js");Web API is a framework designed for creating RESTful HTTP services. It processes JSON or XML payloads to serve desktop applications, mobile apps, or JavaScript-based frontend clients.
// Fully fledged REST API controller configurations
[ApiController]
[Route("api/[controller]")]
public class InventoryController : ControllerBase {
[HttpGet("{id}")]
public IActionResult GetProduct(int id) => Ok(new { ProductId = id });
}SignalR is a real-time web library that enables bi-directional client-server communications over WebSockets, automatically falling back to polling techniques if needed.
// Dynamic server push real-time client sync hubs using SignalR
public class SystemAlertHub : Hub {
public async Task BroadcastAlert(string message) {
await Clients.All.SendAsync("ReceiveAlert", message);
}
}ASP.NET Core Identity is a comprehensive authentication system that manages users, credentials, roles, claims, security tokens, and Multi-Factor Authentication (MFA) setups.
// Complete secure user database schema handling using Microsoft Identity
builder.Services.AddDefaultIdentity<IdentityUser>(options => {
options.Password.RequiredLength = 8;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(15);
}).AddEntityFrameworkStores<ApplicationDbContext>();The Middleware Pipeline defines the sequential execution order of middleware components. Each component decides whether to pass the request to the next step or short-circuit the pipeline.
// Sequence order of middleware layers inside the pipeline
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();Kestrel is the fast, cross-platform, internal HTTP web server engine used in ASP.NET Core applications. It is typically deployed behind a reverse proxy like IIS or Nginx.
// Configuring Kestrel microserver listening sockets in Program.cs
builder.WebHost.ConfigureKestrel(serverOptions => {
serverOptions.ListenAnyIP(5001, listenOptions => {
listenOptions.UseHttps(); // Secure SSL bindings
});
});REST is an architectural design pattern for building distributed web services. It leverages standard HTTP methods to interact with endpoints in a stateless manner.
// Standard REST structural mappings matching standard CRUD verbs
// GET -> api/users (Retrieve collections)
// POST -> api/users (Create record payload)
// PUT -> api/users/{id} (Update record parameters)
// DELETE -> api/users/{id} (Destroy targeted key)JSON Web Token (JWT) is a compact, URL-safe token format used for stateless authentication. The client sends the token in the HTTP Authorization header for authorization validation.
// Creating structural JSON Web Tokens (JWT) inside backend authentication servers
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes("SuperSecretSecureKey123_DoNotDisclose");
var tokenDescriptor = new SecurityTokenDescriptor {
Subject = new ClaimsIdentity(new[] { new Claim("id", "101") }),
Expires = DateTime.UtcNow.AddHours(2),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);Microservices is an architectural style that structures an application as a collection of small, autonomous, loosely-coupled services that communicate via lightweight protocols (e.g., HTTP REST or gRPC).
// Centralized HTTP client configurations interfacing internal microservice APIs
builder.Services.AddHttpClient("BillingService", client => {
client.BaseAddress = new Uri("https://billing.internal.local/");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});The async and await keywords enable non-blocking, asynchronous programming. They improve application scalability by releasing threads to handle other requests while waiting for I/O operations to complete.
// Handling I/O operations non-blockingly via asynchronous threads
public async Task<IActionResult> FetchRecordsAsync() {
var data = await _dbContext.Users.ToListAsync(); // Releases work process thread during database wait
return Ok(data);
}The built-in DI container manages object lifecycles. It supports three service lifetimes: Transient (always recreated), Scoped (recreated per request), and Singleton (one global instance).
// Explicit service registration lifetimes in DI container builds
builder.Services.AddSingleton<ICacheService, MemoryCacheService>(); // Single global instance
builder.Services.AddScoped<IOrderService, OrderService>(); // Recreated per HTTP request context
builder.Services.AddTransient<ITransactionId, GuidGenerator>(); // Recreated on every injection pointCross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts web applications from making requests to a domain different from the one that served the page.
// Configuring dynamic Cross-Origin Resource Sharing (CORS) rules securely
builder.Services.AddCors(options => {
options.AddPolicy("AllowSpecificApp", policy => {
policy.WithOrigins("https://dashboard.company.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});Swagger (OpenAPI) is a toolset that automatically generates interactive REST API documentation, allowing developers to test API endpoints directly from a web browser interface.
// Automated interactive API endpoint schema generators (Swagger)
builder.Services.AddSwaggerGen();
// ...
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Core API v1"));
}ASP.NET Core features a built-in logging interface (ILogger) that writes diagnostics to multiple outputs (e.g., console, files, Azure Application Insights, or third-party tools like Serilog).
// Centralized logging infrastructure configurations in controllers
private readonly ILogger<PaymentController> _logger;
public PaymentController(ILogger<PaymentController> logger) {
_logger = logger;
}
public IActionResult ProcessPayment() {
_logger.LogInformation("Payment sequence initiated dynamically.");
return Ok();
}A basic ASP.NET API Controller demonstrating endpoint routing and returning structured JSON data:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class UserController : ControllerBase {
[HttpGet]
public IActionResult GetUser() {
return Ok(new { Name = "Akash", Role = "Administrator" });
}
}An example of dynamic markup rendering in a Razor view using C# conditionals:
@model WebApp.Models.UserModel
<div className="profile-wrapper">
<h1>Welcome, @Model.Name!</h1>
<p>Account Status: @(Model.IsActive ? "Active" : "Suspended")</p>
</div>An example of dynamic parameter extraction in attribute-based routing:
// Configuring attribute route configurations within standard controllers
[HttpGet("api/v1/departments/{deptId:int}/employees")]
public IActionResult GetEmployeesByDepartment(int deptId) {
return Ok($"Returning employees matching dept: {deptId}");
}How dependencies are resolved automatically via class constructor interfaces:
public interface IService {
string GetServiceData();
}
public class BusinessController : ControllerBase {
private readonly IService _service;
// Dependency Injection resolves the service instance automatically on initialization
public BusinessController(IService service) {
_service = service;
}
}An asynchronous endpoint demonstrating database queries and returning HTTP responses:
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProductById(int id) {
var product = await _dbContext.Products.FindAsync(id);
if (product == null) {
return NotFound(new { Message = "Target item not registered." });
}
return Ok(product);
}An example of storing and reading strings in the HTTP session cache:
// Writing and retrieving operational session properties
HttpContext.Session.SetString("name", "AK");
var cachedSessionUser = HttpContext.Session.GetString("name");An example of dynamic try-catch-finally blocks with structured error logging:
try {
var result = _paymentService.ProcessTransaction(payload);
}
catch (PaymentDeclinedException ex) {
_logger.LogWarning(ex, "Declined transaction processing sequence.");
return BadRequest(ex.Message);
}
catch (Exception ex) {
_logger.LogError(ex, "Unexpected crash inside the transaction processor.");
throw;
}A custom middleware component that executes logic during HTTP requests:
public class SimpleCustomMiddleware {
private readonly RequestDelegate _next;
public SimpleCustomMiddleware(RequestDelegate next) {
_next = next;
}
public async Task InvokeAsync(HttpContext context) {
// Run logic prior to executing down nested steps
context.Response.Headers.Add("X-Execution-Engine", "ASP.NET Core");
await _next(context);
}
}An example of reading connection strings and app settings at runtime:
// Programmatic configurations mappings inside core app pipelines
var databaseConnectionString = Configuration.GetConnectionString("DefaultConnection");
var thirdPartyApiKey = Configuration["ApiKeys:ExternalProvider"];An example of registering and enabling cross-origin policies in the startup pipeline:
// Program.cs setup configuration settings
builder.Services.AddCors(options => {
options.AddPolicy("AllowDashboard", p => p.WithOrigins("https://dash.com").AllowAnyMethod());
});
var app = builder.Build();
app.UseCors("AllowDashboard");