Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.
Answer: Anti-Forgery Tokens Protects against CSRF attacks In Razor: <form method="post"> @Html.AntiForgeryToken() </form> In API: use services.AddAntiforgery(), validate via [ValidateAntiForge…
Creating REST APIs in ASP.NET Core is straightforward using controllers or minimal PIs. Example: Traditional Controller-Based API dotnet new webapi -n MyApi Program.cs: var builder = WebApplication.CreateBuilder(args); b…
pp.UseAuthentication(); pp.UseAuthorization(); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not u…
ASP.NET Core Identity is a membership system that manages users, passwords, roles, claims, and authentication. It provides: User registration & login Password hashing Role & claims management Two-factor authentic…
ASP.NET Core has a built-in Dependency Injection (DI) container, which means you don’t need third-party frameworks like Autofac or Ninject. DI allows you to register classes (services) in a central place and then inject…
MVC stands for Model–View–Controller, a design pattern that separates application logic into three layers: Model – Represents the data and business logic (e.g., Product, Customer, Order). View – The UI or presentation la…
dotnet publish -c Release What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not use it in production R…
Answer: Install package: dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, s…
Answer: Caching improves performance by storing frequently used data in memory or external storage to reduce database or API calls. SP.NET Core provides: What interviewers expect A clear definition tied to MVC in ASP.NET…
Creating REST APIs in ASP.NET Core is straightforward using controllers or minimal APIs. Example: Traditional Controller-Based API dotnet new webapi -n MyApi Program.cs: var builder = WebApplication.CreateBuilder(args);…
Answer: Add secrets: dotnet user-secrets set "ConnectionStrings:Default" "Server=.;Database=Shop;User=sa;Password=12345" What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (pe…
ASP.NET Core configuration is flexible, layered, and environment-aware. It reads settings from multiple sources (JSON files, environment variables, command-line rgs, etc.) and merges them into a single configuration obje…
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationS cheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true…
var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization(); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) W…
options.UseLazyLoadingProxies().UseSqlServer(...); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would n…
Middleware vs Filters vs Handlers Concept When It Runs Scope Example Middleware Before/after request Global Logging, authentication Filters Around controller/action Controller/action Authorization, validation Handlers Au…
dotnet publish -c Release -o C:\inetpub\wwwroot\MyApp What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and woul…
Answer: builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost:6379"; }); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (perfo…
Environment variables are great for overriding settings at deployment time (especially in Docker or Azure). Example: set ASPNETCORE_ENVIRONMENT=Production set ConnectionStrings__Default="Server=mydb;Database=App;User=sa;…
Answer: [Authorize] [ApiController] [Route("api/[controller]")] public class OrdersController : ControllerBase { [HttpGet] public IActionResult GetOrders() => Ok("Secured Orders"); } What interviewers expect A cle…
Answer: public class ApplicationUser : IdentityUser { public string FullName { get; set; } } What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability,…
Follow : What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not use it in production Real-world example…
public virtual Category Category { get; set; } What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not u…
SignalR vs WebSockets Feature WebSockets SignalR Protocol Low-level TCP-based High-level abstraction Transpor Only WebSockets Fallbacks: WebSockets → SSE → Long Polling Usage Real-time messages Real-time hubs with automa…
How to Host in Azure App Service? Answer: Azure App Service provides PaaS hosting for ASP.NET Core apps. Steps: Publish the app via Visual Studio, CLI, or GitHub Actions. dotnet publish -c Release Create App Service in A…
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: Anti-Forgery Tokens Protects against CSRF attacks In Razor: <form method="post"> @Html.AntiForgeryToken() </form> In API: use services.AddAntiforgery(), validate via [ValidateAntiForgeryToken]. 1⃣
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Creating REST APIs in ASP.NET Core is straightforward using controllers or minimal
PIs.
Example: Traditional Controller-Based API
dotnet new webapi -n MyApi
Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
pp.MapControllers();
pp.Run();
Controller:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok(new[] { "Laptop", "Phone"
});
}
✅ You get RESTful endpoints automatically (GET /api/products).
🧱 2. What is the [ApiController] attribute?
[ApiController] simplifies building APIs by adding smart defaults:
Example:
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
[HttpPost]
public IActionResult CreateOrder(Order order)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
return CreatedAtAction(nameof(CreateOrder), new { id = 1 },
order);
}
}
📦 3. How does content negotiation work?
Content negotiation allows clients to request responses in a specific format (JSON, XML,
etc.) using the Accept header.
SP.NET Core automatically picks the best formatter:
GET /api/products
ccept: application/json
Response → JSON
GET /api/products
ccept: application/xml
Response → XML (if XML formatter is added)
Enable XML Support:
builder.Services.AddControllers()
.AddXmlSerializerFormatters();
🧭 4. How to handle versioning in APIs?
You can version APIs to maintain backward compatibility using the
Microsoft.AspNetCore.Mvc.Versioning package.
Install:
dotnet add package Microsoft.AspNetCore.Mvc.Versioning
Configure:
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
Use in controllers:
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV1Controller : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("Version 1");
}
⚠ 5. What is ProblemDetails?
ProblemDetails is a standardized JSON structure for API error responses (RFC 7807).
Example Output:
{
"type": "
"title": "Resource not found",
"status": 404,
"detail": "Product with ID 5 was not found"
}
Usage:
return NotFound(new ProblemDetails
{
Title = "Product not found",
Status = StatusCodes.Status404NotFound,
Detail = "The product ID 5 does not exist."
});
🚦 6. How to return custom HTTP status codes?
You can use built-in helpers from ControllerBase:
Method Status
Code
Ok() 200
Created() /
CreatedAtAction()
201
NoContent() 204
BadRequest() 400
Unauthorized() 401
NotFound() 404
StatusCode(500) Custom
Example:
return StatusCode(503, "Service temporarily unavailable");
📄 7. How to implement pagination in APIs?
Pagination helps manage large datasets efficiently.
Example:
[HttpGet]
public IActionResult GetProducts([FromQuery] int page = 1,
[FromQuery] int size = 10)
{
var data = _context.Products
.Skip((page - 1) * size)
.Take(size)
.ToList();
var totalCount = _context.Products.Count();
Response.Headers.Add("X-Total-Count", totalCount.ToString());
return Ok(data);
}
✅ Supports GET /api/products?page=2&size=5.
🔐 8. How to secure APIs with JWT tokens?
Use JWT (JSON Web Token) authentication for stateless security.
Setup in Program.cs:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationS
cheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new
TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "
ValidateAudience = true,
ValidAudience = "
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("super-secret-key"))
};
});
Then protect controllers:
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult GetOrders() => Ok("Secure data");
}
⚡ 9. What is rate limiting in .NET 8?
.NET 8 introduces built-in rate limiting middleware to control API request rates.
Example:
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("fixed", opt =>
{
opt.PermitLimit = 5; // 5 requests
opt.Window = TimeSpan.FromSeconds(10); // per 10 seconds
opt.QueueLimit = 0;
});
});
var app = builder.Build();
pp.UseRateLimiter();
pp.MapGet("/api/data", () => "Hello")
.RequireRateLimiting("fixed");
✅ Prevents abuse or DDoS attacks by throttling requests.
🚨 10. How do you handle exceptions in APIs?
Use global exception handling middleware instead of try/catch everywhere.
Example:
pp.UseExceptionHandler("/error");
pp.Map("/error", (HttpContext context) =>
{
var exception =
context.Features.Get<IExceptionHandlerFeature>()?.Error;
return Results.Problem(title: "Unexpected error", detail:
exception?.Message);
});
Or write a custom middleware for consistent error formatting.
🧾 11. How to use Swagger / OpenAPI?
Swagger generates interactive API documentation automatically.
Setup:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
pp.UseSwagger();
pp.UseSwaggerUI();
}
Run → Navigate to
✅ You can test endpoints directly from the browser.
🧰 12. What is NSwag or Swashbuckle?
Both tools generate OpenAPI/Swagger documentation, but with slight differences:
Tool Description
Swashbuckle.AspNetCor
Most common; adds Swagger UI, docs, and JSON schema
NSwag Adds extra features like client SDK generation for
C#/TypeScript
Example (NSwag client generation):
nswag openapi2csclient
/input:
/output:Client.cs
📤 13. How to upload files via Web API?
Use IFormFile for file uploads.
Controller Example:
[HttpPost("upload")]
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file == null || file.Length == 0)
return BadRequest("No file uploaded.");
var path = Path.Combine("wwwroot/uploads", file.FileName);
using var stream = new FileStream(path, FileMode.Create);
wait file.CopyToAsync(stream);
return Ok(new { file.FileName, file.Length });
}
Client sends multipart/form-data POST requests.
🌐 14. How to implement CORS?
CORS (Cross-Origin Resource Sharing) allows requests from other domains (e.g., frontend
pps).
Enable in Program.cs:
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowReactApp",
policy => policy.WithOrigins("
.AllowAnyHeader()
.AllowAnyMethod());
});
var app = builder.Build();
pp.UseCors("AllowReactApp");
✅ Now your React or Angular frontend can call your API safely.
🚀 15. What’s new in .NET 8 Minimal APIs?
Minimal APIs let you build lightweight REST endpoints without controllers — great for
microservices.
Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
pp.MapGet("/products", () => new[] { "Phone", "Tablet" });
pp.MapPost("/products", (Product product) =>
Results.Created($"/products/{product.Id}", product));
pp.Run();
New in .NET 8:
✅ Minimal APIs now rival traditional controllers for small, fast APIs.
Performance & Caching
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
pp.UseAuthentication(); pp.UseAuthorization();
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
ASP.NET Core Identity is a membership system that manages users, passwords, roles,
claims, and authentication.
It provides:
Example:
You can scaffold Identity to get ready-to-use pages for login, registration, and password
reset.
⚙ 2. How do you configure Identity in ASP.NET Core?
Add Identity services in Program.cs:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("Defa
ultConnection")));
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
ASP.NET Core has a built-in Dependency Injection (DI) container, which means you
don’t need third-party frameworks like Autofac or Ninject.
DI allows you to register classes (services) in a central place and then inject them
wherever they’re needed. This promotes loose coupling, testability, and maintainability.
Example:
public interface IEmailService
{
void Send(string to, string subject, string body);
}
public class EmailService : IEmailService
{
public void Send(string to, string subject, string body)
=> Console.WriteLine($"Email sent to {to}");
}
Register it in Program.cs:
builder.Services.AddScoped<IEmailService, EmailService>();
Use it in a controller:
public class AccountController : Controller
{
private readonly IEmailService _emailService;
public AccountController(IEmailService emailService)
{
_emailService = emailService;
}
public IActionResult Register()
{
_emailService.Send("user@example.com", "Welcome!", "Thanks
for joining!");
return View();
}
}
🔁 2. What is the lifetime of services (Transient,
Scoped, Singleton)?
SP.NET Core provides three lifetimes for services:
Lifetime Description Example Use Case
Transien
new instance is created every time
the service is requested.
Lightweight, stateless services like
formatters or mappers.
Scoped A new instance is created per HTTP
request.
Database contexts, unit of work
patterns.
Singleto
single instance for the entire app
lifetime.
Configuration, caching, or logging
services.
Example:
builder.Services.AddTransient<IFormatter, TextFormatter>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddSingleton<IAppCache, MemoryAppCache>();
Tip: Scoped is most common for web apps — e.g., DbContext.
🧱 3. How do you inject dependencies into controllers?
ASP.NET Core automatically uses constructor injection for controllers.
The DI container will look at the constructor parameters and inject registered services.
Example:
public class OrderController : Controller
{
private readonly IOrderService _orderService;
public OrderController(IOrderService orderService)
{
_orderService = orderService;
}
public IActionResult Index() => View(_orderService.GetAll());
}
You don’t manually create OrderService; the framework does.
🔄 4. How do you resolve dependencies in
middleware?
Middleware is created once at startup, so you can’t inject scoped services directly into its
constructor.
Instead, you resolve them inside the Invoke method using the
HttpContext.RequestServices.
Example:
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
var logger =
context.RequestServices.GetRequiredService<ILogger<LoggingMiddleware
>>();
logger.LogInformation("Request path: " +
context.Request.Path);
wait _next(context);
}
}
Register it:
pp.UseMiddleware<LoggingMiddleware>();
🧰 5. How to use IServiceProvider?
IServiceProvider is the built-in service resolver. You can use it to manually resolve
registered dependencies.
Example:
var serviceProvider = builder.Services.BuildServiceProvider();
var emailService =
serviceProvider.GetRequiredService<IEmailService>();
emailService.Send("user@example.com", "Test", "DI working!");
In general:
⚠ 6. What happens if a scoped service is injected into
singleton?
That’s a lifetime mismatch — it causes problems because:
If a singleton holds a reference to a scoped service, that scoped instance never gets
released — leading to memory leaks and unexpected data sharing across requests.
Solution:
public class ReportGenerator
{
private readonly IServiceProvider _provider;
public ReportGenerator(IServiceProvider provider) => _provider =
provider;
public void Generate()
{
using var scope = _provider.CreateScope();
var db =
scope.ServiceProvider.GetRequiredService<AppDbContext>();
// Use db safely here
}
}
🧩 7. How to register multiple implementations for an
interface?
Sometimes you may have multiple implementations of the same interface — you can
register all of them and inject IEnumerable<T>.
Example:
builder.Services.AddTransient<INotificationService,
EmailNotification>();
builder.Services.AddTransient<INotificationService,
SmsNotification>();
Then:
public class NotificationManager
{
private readonly IEnumerable<INotificationService> _services;
public NotificationManager(IEnumerable<INotificationService>
services)
{
_services = services;
}
public void NotifyAll(string message)
{
foreach (var service in _services)
service.Send(message);
}
}
This will call both EmailNotification and SmsNotification.
🧱 8. What is TryAdd in dependency injection?
TryAdd methods (from
Microsoft.Extensions.DependencyInjection.Extensions) register a service
only if it’s not already registered.
Example:
builder.Services.TryAddScoped<ILogService, DefaultLogService>();
If another part of the code already registered a custom ILogService, this one won’t
override it.
Use Case:
When writing reusable libraries or frameworks that should allow overriding defaults.
⚙ 9. How do you inject configuration or options into
services?
You can bind configuration sections (from appsettings.json) to strongly typed
classes and inject them using IOptions<T>.
Example:
// appsettings.json
{
"SmtpSettings": {
"Host": "smtp.mailtrap.io",
"Port": 2525
}
}
Model:
public class SmtpSettings
{
public string Host { get; set; }
public int Port { get; set; }
}
Register:
builder.Services.Configure<SmtpSettings>(
builder.Configuration.GetSection("SmtpSettings"));
Use in service:
public class EmailService
{
private readonly SmtpSettings _settings;
public EmailService(IOptions<SmtpSettings> options)
{
_settings = options.Value;
}
}
🧠 10. What are IOptions, IOptionsSnapshot, and
IOptionsMonitor?
Interface Scope Use Case
IOptions<T> Singleton Read config at startup — doesn’t change at
runtime.
IOptionsSnapshot<T
Scoped (per
request)
Re-reads configuration on each request.
Useful in web apps.
IOptionsMonitor<T> Singleton, listens
for changes
utomatically updates when config changes
(great for dynamic reloading).
Example:
public class MyService
{
private readonly IOptionsMonitor<SmtpSettings> _settings;
public MyService(IOptionsMonitor<SmtpSettings> settings)
{
_settings = settings;
}
public void SendMail()
{
Console.WriteLine($"Sending using host:
{_settings.CurrentValue.Host}");
}
}
If you change appsettings.json and
configuration reload is enabled,
IOptionsMonitor picks up the new
value without restarting the app.
Entity Framework Core
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
MVC stands for Model–View–Controller, a design pattern that separates application logic
into three layers:
Order).
(views or data).
Example:
user requests /Products/Details/1 →
ProductsController.Details(1) → fetches product → returns the
Details.cshtml view.
This separation makes the app more maintainable and testable.
⚙ 2. How are controllers activated in ASP.NET Core?
Controllers are created by the ControllerActivator, which uses Dependency Injection (DI)
to resolve dependencies.
You don’t manually instantiate controllers — the framework does it for you.
Example:
public class ProductsController : Controller
{
private readonly IProductService _service;
public ProductsController(IProductService service) => _service =
service;
}
When a request matches the route /products, the DI container automatically provides
IProductService.
🧱 3. What is the role of the ControllerBase and
Controller classes?
routing, model binding, and IActionResult.
ViewBag, etc.).
Example:
// For APIs
public class ProductApiController : ControllerBase { }
// For MVC Views
public class ProductController : Controller { }
🔗 4. What is the difference between Controller and
piController?
Feature Controller ApiController
Purpose Returns views (HTML) Returns data (JSON/XML)
Inheritanc
Controller ControllerBase with
[ApiController]
Features ViewBag, View(), PartialView() Automatic model validation, attribute routing
Example return View(product); return Ok(product);
⚡ 5. What are Action Methods?
Action methods are public methods in a controller that handle HTTP requests.
Example:
public class ProductController : Controller
{
public IActionResult Details(int id)
{
var product = _service.GetById(id);
return View(product);
}
}
Notes:
🎯 6. What are Action Results?
An Action Result represents the response returned to the client — view, JSON, redirect,
file, etc.
SP.NET Core provides many result types:
🔍 7. Difference between ViewResult, JsonResult, and
ContentResult.
Type Used For Example
ViewResult Returns an HTML view return View("Details",
model);
JsonResult Returns JSON data return Json(model);
ContentResul
Returns plain text or custom
content
return Content("Hello
World");
IActionResult is an interface that represents the result of an action method.
It allows flexibility — you can return any kind of result (view, JSON, redirect, etc.) from the
same method.
Example:
public IActionResult Index()
{
if (!User.Identity.IsAuthenticated)
return RedirectToAction("Login");
return View();
}
🧠 9. How does model binding work?
Model binding automatically maps data from the HTTP request (query string, route, body,
form) to method parameters or model objects.
Example:
public IActionResult Save(Product model)
{
// model properties are automatically filled
_service.Add(model);
return RedirectToAction("Index");
}
If the request body contains { "Name": "Laptop", "Price": 1200 },
SP.NET Core binds it to the Product object.
✅ 10. How does model validation work?
Model validation checks whether the incoming model meets data annotation rules before
executing the action.
Example:
public class Product
{
[Required]
public string Name { get; set; }
[Range(1, 10000)]
public decimal Price { get; set; }
}
In a controller:
if (!ModelState.IsValid)
return View(model);
If [ApiController] is used, invalid models automatically return 400 Bad Request.
🧩 11. What are filters in ASP.NET Core MVC?
Filters are components that allow code to run before or after specific stages of request
processing in MVC — e.g., authorization, action execution, results, etc.
They provide cross-cutting concerns like logging, caching, or exception handling.
🧱 12. Explain different types of filters.
Filter Type Purpose Runs When
uthorization Filter Checks if user is authorized Before everything
Resource Filter Run before/after model binding Around action
ction Filter Run before/after action
methods
round controller actions
Exception Filter Handle unhandled exceptions When an exception
occurs
Result Filter Run before/after action results Around result execution
🔢 13. What is filter ordering?
Filters run in a specific order:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
dotnet publish -c Release
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: Install package: dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: Caching improves performance by storing frequently used data in memory or external storage to reduce database or API calls. SP.NET Core provides:
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Creating REST APIs in ASP.NET Core is straightforward using controllers or minimal
APIs.
Example: Traditional Controller-Based API
dotnet new webapi -n MyApi
Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
Controller:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
[HttpGet]
public IActionResult GetAll() => Ok(new[] { "Laptop", "Phone"
});
✅ You get RESTful endpoints automatically (GET /api/products).
🧱 2. What is the [ApiController] attribute?
[ApiController] simplifies building APIs by adding smart defaults:
Follow :
Example:
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
[HttpPost]
public IActionResult CreateOrder(Order order)
if (!ModelState.IsValid)
return BadRequest(ModelState);
return CreatedAtAction(nameof(CreateOrder), new { id = 1 },
order);
📦 3. How does content negotiation work?
Content negotiation allows clients to request responses in a specific format (JSON, XML,
etc.) using the Accept header.
ASP.NET Core automatically picks the best formatter:
GET /api/products
Accept: application/json
Response → JSON
GET /api/products
Accept: application/xml
Response → XML (if XML formatter is added)
Follow :
Enable XML Support:
builder.Services.AddControllers()
.AddXmlSerializerFormatters();
🧭 4. How to handle versioning in APIs?
You can version APIs to maintain backward compatibility using the
Microsoft.AspNetCore.Mvc.Versioning package.
Install:
dotnet add package Microsoft.AspNetCore.Mvc.Versioning
Configure:
builder.Services.AddApiVersioning(options =>
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
Use in controllers:
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV1Controller : ControllerBase
[HttpGet]
public IActionResult Get() => Ok("Version 1");
⚠ 5. What is ProblemDetails?
Follow :
ProblemDetails is a standardized JSON structure for API error responses (RFC 7807).
Example Output:
"type": "
"title": "Resource not found",
"status": 404,
"detail": "Product with ID 5 was not found"
Usage:
return NotFound(new ProblemDetails
Title = "Product not found",
Status = StatusCodes.Status404NotFound,
Detail = "The product ID 5 does not exist."
});
🚦 6. How to return custom HTTP status codes?
You can use built-in helpers from ControllerBase:
Method Status
Code
Ok() 200
Created() /
CreatedAtAction()
201
NoContent() 204
BadRequest() 400
Unauthorized() 401
Follow :
NotFound() 404
StatusCode(500) Custom
Example:
return StatusCode(503, "Service temporarily unavailable");
📄 7. How to implement pagination in APIs?
Pagination helps manage large datasets efficiently.
Example:
[HttpGet]
public IActionResult GetProducts([FromQuery] int page = 1,
[FromQuery] int size = 10)
var data = _context.Products
.Skip((page - 1) * size)
.Take(size)
.ToList();
var totalCount = _context.Products.Count();
Response.Headers.Add("X-Total-Count", totalCount.ToString());
return Ok(data);
✅ Supports GET /api/products?page=2&size=5.
🔐 8. How to secure APIs with JWT tokens?
Use JWT (JSON Web Token) authentication for stateless security.
Follow :
Setup in Program.cs:
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationS
cheme)
.AddJwtBearer(options =>
options.TokenValidationParameters = new
TokenValidationParameters
ValidateIssuer = true,
ValidIssuer = "
ValidateAudience = true,
ValidAudience = "
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("super-secret-key"))
});
Then protect controllers:
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
[HttpGet]
public IActionResult GetOrders() => Ok("Secure data");
⚡ 9. What is rate limiting in .NET 8?
.NET 8 introduces built-in rate limiting middleware to control API request rates.
Example:
builder.Services.AddRateLimiter(options =>
Follow :
options.AddFixedWindowLimiter("fixed", opt =>
opt.PermitLimit = 5; // 5 requests
opt.Window = TimeSpan.FromSeconds(10); // per 10 seconds
opt.QueueLimit = 0;
});
});
var app = builder.Build();
app.UseRateLimiter();
app.MapGet("/api/data", () => "Hello")
.RequireRateLimiting("fixed");
✅ Prevents abuse or DDoS attacks by throttling requests.
🚨 10. How do you handle exceptions in APIs?
Use global exception handling middleware instead of try/catch everywhere.
Example:
app.UseExceptionHandler("/error");
app.Map("/error", (HttpContext context) =>
var exception =
context.Features.Get<IExceptionHandlerFeature>()?.Error;
return Results.Problem(title: "Unexpected error", detail:
exception?.Message);
});
Or write a custom middleware for consistent error formatting.
Follow :
🧾 11. How to use Swagger / OpenAPI?
Swagger generates interactive API documentation automatically.
Setup:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
app.UseSwagger();
app.UseSwaggerUI();
Run → Navigate to
✅ You can test endpoints directly from the browser.
🧰 12. What is NSwag or Swashbuckle?
Both tools generate OpenAPI/Swagger documentation, but with slight differences:
Tool Description
Swashbuckle.AspNetCor
Most common; adds Swagger UI, docs, and JSON schema
NSwag Adds extra features like client SDK generation for
C#/TypeScript
Example (NSwag client generation):
Follow :
nswag openapi2csclient
/input:
/output:Client.cs
📤 13. How to upload files via Web API?
Use IFormFile for file uploads.
Controller Example:
[HttpPost("upload")]
public async Task<IActionResult> UploadFile(IFormFile file)
if (file == null || file.Length == 0)
return BadRequest("No file uploaded.");
var path = Path.Combine("wwwroot/uploads", file.FileName);
using var stream = new FileStream(path, FileMode.Create);
await file.CopyToAsync(stream);
return Ok(new { file.FileName, file.Length });
Client sends multipart/form-data POST requests.
🌐 14. How to implement CORS?
CORS (Cross-Origin Resource Sharing) allows requests from other domains (e.g., frontend
apps).
Enable in Program.cs:
builder.Services.AddCors(options =>
Follow :
options.AddPolicy("AllowReactApp",
policy => policy.WithOrigins("
.AllowAnyHeader()
.AllowAnyMethod());
});
var app = builder.Build();
app.UseCors("AllowReactApp");
✅ Now your React or Angular frontend can call your API safely.
🚀 15. What’s new in .NET 8 Minimal APIs?
Minimal APIs let you build lightweight REST endpoints without controllers — great for
microservices.
Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/products", () => new[] { "Phone", "Tablet" });
app.MapPost("/products", (Product product) =>
Results.Created($"/products/{product.Id}", product));
app.Run();
New in .NET 8:
Follow :
✅ Minimal APIs now rival traditional controllers for small, fast APIs.
Performance & Caching
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: Add secrets: dotnet user-secrets set "ConnectionStrings:Default" "Server=.;Database=Shop;User=sa;Password=12345"
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
ASP.NET Core configuration is flexible, layered, and environment-aware.
It reads settings from multiple sources (JSON files, environment variables, command-line
rgs, etc.) and merges them into a single configuration object (IConfiguration).
Example:
In Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Access configuration
var appName = builder.Configuration["AppSettings:Name"];
SP.NET Core automatically loads:
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationS
cheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new
TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "
ValidAudience = "
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("super-secret-key-123"))
};
});
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
var app = builder.Build(); app.UseAuthentication(); app.UseAuthorization();
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
options.UseLazyLoadingProxies().UseSqlServer(...);
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Middleware vs Filters vs Handlers
Concept When It Runs Scope Example
Middleware Before/after request Global Logging, authentication
Filters Around controller/action Controller/action Authorization, validation
Handlers Authentication/Authorization Global or
endpoint
JWT handler, Cookie
auth
1⃣
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
dotnet publish -c Release -o C:\inetpub\wwwroot\MyApp
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost:6379"; });
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Environment variables are great for overriding settings at deployment time (especially in
Docker or Azure).
Example:
set ASPNETCORE_ENVIRONMENT=Production
set
ConnectionStrings__Default="Server=mydb;Database=App;User=sa;Passwor
d=123"
Notice the double underscores __ for nested keys.
Then access in code:
var conn = builder.Configuration["ConnectionStrings:Default"];
🧭 6. What are the common environment names?
SP.NET Core defines three common hosting environments:
Environment Purpose
Developmen
Local development, detailed errors, hot reload
Staging Pre-production testing
Production Live environment, performance optimized, no detailed errors
You set the environment via:
set ASPNETCORE_ENVIRONMENT=Development
🔍 7. How do you detect the current environment?
You can inject or access the IWebHostEnvironment or IHostEnvironment service.
Example:
public class HomeController : Controller
{
private readonly IWebHostEnvironment _env;
public HomeController(IWebHostEnvironment env)
{
_env = env;
}
public IActionResult Index()
{
if (_env.IsDevelopment())
return Content("Running in Development mode");
return Content($"Environment: {_env.EnvironmentName}");
}
}
You can also access it in Program.cs:
if (builder.Environment.IsProduction())
{
// Configure production services
}
🧾 8. How to use different appsettings.json files?
ASP.NET Core supports environment-specific JSON files.
Example structure:
ppsettings.json
ppsettings.Development.json
ppsettings.Staging.json
ppsettings.Production.json
Program.cs:
builder.Configuration
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.jso
n", optional: true);
t runtime, only the file matching the current environment will override base settings.
Example:
ppsettings.json
{ "AppName": "MyApp", "LogLevel": "Information" }
ppsettings.Production.json
{ "LogLevel": "Error" }
Result in Production → LogLevel = Error.
🔄 9. How to reload configuration dynamically?
You can make JSON configuration files auto-reload when changed.
Example:
builder.Configuration.AddJsonFile("appsettings.json", optional:
false, reloadOnChange: true);
If you update appsettings.json, the new values are reflected automatically in your app
without restarting.
You can subscribe to changes using IOptionsMonitor (see below).
📦 10. How to bind configuration to POCO classes?
You can map sections of your configuration directly to C# classes (POCOs).
Example:
ppsettings.json
{
"AppSettings": {
"SiteName": "TechStore",
"PageSize": 20,
"EnableCache": true
}
}
Create a POCO:
public class AppSettings
{
public string SiteName { get; set; }
public int PageSize { get; set; }
public bool EnableCache { get; set; }
}
Bind configuration:
builder.Services.Configure<AppSettings>(
builder.Configuration.GetSection("AppSettings"));
Inject it into a controller:
public class HomeController : Controller
{
private readonly AppSettings _settings;
public HomeController(IOptions<AppSettings> options)
{
_settings = options.Value;
}
public IActionResult Index()
{
return Content($"Welcome to {_settings.SiteName}!");
}
}
You can also use IOptionsSnapshot for per-request reload or IOptionsMonitor for live
updates.
Web APIs & REST
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: [Authorize] [ApiController] [Route("api/[controller]")] public class OrdersController : ControllerBase { [HttpGet] public IActionResult GetOrders() => Ok("Secured Orders"); }
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Answer: public class ApplicationUser : IdentityUser { public string FullName { get; set; } }
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
Follow :
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
public virtual Category Category { get; set; }
In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.
Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
SignalR vs WebSockets
Feature WebSockets SignalR
Protocol Low-level
TCP-based
High-level abstraction
Transpor
Only WebSockets Fallbacks: WebSockets → SSE → Long Polling
Usage Real-time
messages
Real-time hubs with automatic reconnection, grouping,
scaling
✅ Use SignalR for apps needing broadcast, connection management, and fallbacks.
ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC
How to Host in Azure App Service?
Answer:
Azure App Service provides PaaS hosting for ASP.NET Core apps.
Steps:
dotnet publish -c Release
✅ Supports scaling, HTTPS, and monitoring out-of-the-box.