Interview Q&A

Technical interview questions with detailed answers—organized by course, like Dot Net Tutorials interview sections. Original content for Toolliyo Academy.

Popular tracks

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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:

  • User registration & login
  • Password hashing
  • Role & claims management
  • Two-factor authentication
  • Cookie & token-based authentication

Example:

You can scaffold Identity to get ready-to-use pages for login, registration, and password

reset.

Follow :

⚙ 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();

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

var app = builder.Build();

app.UseAuthentication();

app.UseAuthorization();

Permalink

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"))

});

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

ASP.NET Core configuration is flexible, layered, and environment-aware.

Follow :

It reads settings from multiple sources (JSON files, environment variables, command-line

args, 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"];

ASP.NET Core automatically loads:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Add secrets:

dotnet user-secrets set "ConnectionStrings:Default"

"Server=.;Database=Shop;User=sa;Password=12345"

Permalink

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:

  • Automatic model validation → 400 Bad Request on invalid models
  • Automatic [FromBody], [FromQuery], etc. inference

Follow :

  • ProblemDetails JSON response for errors

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:

  • Route groups for grouping endpoints
  • Input validation with [Validate] attributes
  • Enhanced OpenAPI (Swagger) support
  • Rate limiting, Authorization, and Filters integration

Follow :

  • Typed results for consistent HTTP responses

✅ Minimal APIs now rival traditional controllers for small, fast APIs.

Performance & Caching

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Caching improves performance by storing frequently used data in memory or external

storage to reduce database or API calls.

ASP.NET Core provides:

Permalink

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:

Follow :

  • Model – Represents the data and business logic (e.g., Product, Customer,

Order).

  • View – The UI or presentation layer that displays data (Razor views).
  • Controller – Handles user requests, interacts with the model, and returns responses

(views or data).

Example:

A 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.

Follow :

🧱 3. What is the role of the ControllerBase and

Controller classes?

  • ControllerBase: Base class for API controllers — includes core MVC features like

routing, model binding, and IActionResult.

  • Controller: Inherits from ControllerBase and adds View support (e.g., View(),

ViewBag, etc.).

Example:

// For APIs

public class ProductApiController : ControllerBase { }

// For MVC Views

public class ProductController : Controller { }

🔗 4. What is the difference between Controller and

ApiController?

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.

Follow :

Example:

public class ProductController : Controller

public IActionResult Details(int id)

var product = _service.GetById(id);

return View(product);

Notes:

  • Action methods cannot be private or static.
  • They respond to routes like /Product/Details/5.

🎯 6. What are Action Results?

An Action Result represents the response returned to the client — view, JSON, redirect,

file, etc.

ASP.NET Core provides many result types:

  • ViewResult
  • JsonResult
  • RedirectResult
  • FileResult
  • ContentResult
  • StatusCodeResult

Follow :

🔍 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");

🔹 8. What is IActionResult?

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:

Follow :

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 },

ASP.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?

Follow :

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

Authorization Filter Checks if user is authorized Before everything

Resource Filter Run before/after model binding Around action

Action Filter Run before/after action

methods

Around 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:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Install package:

dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

dotnet publish -c Release

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

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);

Follow :

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)?

ASP.NET Core provides three lifetimes for services:

Lifetime Description Example Use Case

Follow :

Transien

A 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

A 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.

Follow :

🔄 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);

await _next(context);

Register it:

app.UseMiddleware<LoggingMiddleware>();

🧰 5. How to use IServiceProvider?

IServiceProvider is the built-in service resolver. You can use it to manually resolve

registered dependencies.

Follow :

Example:

var serviceProvider = builder.Services.BuildServiceProvider();

var emailService =

serviceProvider.GetRequiredService<IEmailService>();

emailService.Send("user@example.com", "Test", "DI working!");

In general:

  • Use IServiceProvider sparingly — prefer constructor injection.
  • Good for scenarios like custom factories or background tasks.

⚠ 6. What happens if a scoped service is injected into

a singleton?

That’s a lifetime mismatch — it causes problems because:

  • The singleton lives for the app’s lifetime.
  • The scoped service lives only for a single request.

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:

  • Don’t inject scoped services into singletons.
  • Instead, inject an IServiceProvider and create a scope manually when needed:

public class ReportGenerator

private readonly IServiceProvider _provider;

Follow :

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;

Follow :

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

Follow :

"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

Follow :

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

Automatically 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.

Follow :

Entity Framework Core

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Entity Framework Core (EF Core) is a modern, lightweight, cross-platform ORM (Object

Relational Mapper) from Microsoft.

It allows .NET developers to work with databases using .NET objects, without writing most

SQL manually.

EF Core handles:

  • Mapping classes → database tables
  • LINQ → SQL translation
  • Tracking changes
  • Saving data (SaveChanges())

Example:

var product = new Product { Name = "Laptop", Price = 1200 };

_context.Products.Add(product);

_context.SaveChanges();

This automatically executes an INSERT statement in the database.

⚙ 2. What are the differences between EF Core and EF

Feature EF 6 EF Core

Platform .NET Framework only Cross-platform (.NET 6/7/8)

Follow :

Architecture Monolithic Modular, lightweight

LINQ Support Mature, stable Constantly improving

Lazy Loading Built-in Requires setup

Migrations Code-based Improved and more flexible

Database

Providers

Limited (SQL Server,

etc.)

Many (PostgreSQL, MySQL, SQLite, Cosmos

DB, etc.)

Performance Slower Much faster, optimized

EF Core is not just EF 6 ported — it was rewritten from scratch for .NET Core.

🧱 3. How do you configure DbContext in ASP.NET

Core?

DbContext represents a session with the database — it’s where you query and save data.

You register it in the dependency injection container inside Program.cs.

Example:

builder.Services.AddDbContext<AppDbContext>(options =>

options.UseSqlServer(builder.Configuration.GetConnectionString("Defa

ultConnection")));

AppDbContext class:

public class AppDbContext : DbContext

public AppDbContext(DbContextOptions<AppDbContext> options) :

base(options) { }

public DbSet<Product> Products { get; set; }

Follow :

🧱 4. What are Migrations?

Migrations allow you to evolve your database schema as your models change, without

losing existing data.

Commands:

dotnet ef migrations add InitialCreate

dotnet ef database update

This creates a Migrations folder with code that applies schema changes automatically.

🧩 5. What is the OnModelCreating method used for?

OnModelCreating is where you configure entity behavior and relationships using the

Fluent API.

Example:

protected override void OnModelCreating(ModelBuilder modelBuilder)

modelBuilder.Entity<Product>()

.Property(p => p.Name)

.HasMaxLength(100)

.IsRequired();

modelBuilder.Entity<Order>()

.HasMany(o => o.Items)

.WithOne(i => i.Order)

.HasForeignKey(i => i.OrderId);

Use it for constraints, relationships, indexes, seeding, and more.

Follow :

💤 6. How do you enable Lazy Loading in EF Core?

Lazy loading means related entities are loaded automatically when accessed.

To enable it:

Install the package:

dotnet add package Microsoft.EntityFrameworkCore.Proxies

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

options.UseLazyLoadingProxies().UseSqlServer(...);

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

ASP.NET Core is a cross-platform, open-source framework for building modern web

applications, APIs, and microservices. It’s a complete rewrite of the old ASP.NET

framework, designed to be lightweight, modular, and cloud-ready.

Key Differences:

Feature ASP.NET MVC 5 ASP.NET Core

Platform Windows only Cross-platform (Windows, macOS, Linux)

Hosting IIS only Kestrel, IIS, Nginx, Apache, self-hosting

Configuration web.config (XML) appsettings.json (JSON-based)

Dependency Injection Third-party libraries Built-in DI container

Modularity Monolithic Modular via NuGet packages

Example:

In ASP.NET MVC 5, you’d deploy only to IIS on Windows. In ASP.NET Core, the same app

can run on a Linux server using Nginx + Kestrel — perfect for Docker or cloud

environments.

⚙ 2. Explain the request-processing pipeline in

ASP.NET Core.

ASP.NET Core handles incoming requests through a middleware pipeline. Each

middleware can process, modify, or short-circuit requests before they reach the endpoint.

Flow Example:

Request → Middleware 1 (Logging)

→ Middleware 2 (Authentication)

→ Middleware 3 (Routing)

→ Controller / Endpoint

→ Response → Back through pipeline

Follow :

Example:

If you log requests, check authentication, and handle static files — they execute in the order

you add them in Program.cs.

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

🧱 3. What is Kestrel?

Kestrel is a cross-platform web server built into ASP.NET Core. It’s fast, lightweight, and

serves as the default web server. You can run it standalone or behind a reverse proxy like

IIS or Nginx.

Real Example:

When you run dotnet run, your app listens on

— that’s

Kestrel serving your app.

🖥 4. What is the role of IIS when hosting ASP.NET

Core apps?

IIS acts as a reverse proxy. It forwards incoming HTTP requests to the Kestrel server

running your ASP.NET Core app. This setup provides:

  • Process management (auto-restart)
  • Port sharing (multiple sites)
  • Windows authentication
  • Logging and monitoring

Follow :

In short: IIS → forwards → Kestrel → runs the app.

🚀 5. What is the Startup class used for?

The Startup class defines how your app configures services (DI, authentication, etc.)

and sets up middleware (routing, static files, error pages, etc.).

Example:

public class Startup

public void ConfigureServices(IServiceCollection services)

services.AddControllers();

public void Configure(IApplicationBuilder app)

app.UseRouting();

app.UseEndpoints(endpoints => endpoints.MapControllers());

🧭 6. Explain the purpose of Program.cs in .NET 6+.

In .NET 6+, Startup.cs and Program.cs merged into one minimal host configuration

file.

It sets up the web host, configuration, logging, and middleware pipeline.

Example:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

Follow :

app.MapControllers();

app.Run();

It’s simpler, faster, and easier to read.

🔹 7. What is a Minimal API?

Minimal APIs are a lightweight way to build small HTTP APIs without controllers or

attributes. Perfect for microservices.

Example:

var app = WebApplication.Create(args);

app.MapGet("/hello", () => "Hello World!");

app.Run();

This single file can run a full REST endpoint.

🧰 8. What is the WebApplicationBuilder in .NET 6/7/8?

WebApplicationBuilder simplifies creating and configuring a web host. It combines:

  • IHostBuilder
  • WebHostBuilder
  • Configuration
  • Services

Example:

var builder = WebApplication.CreateBuilder(args);

Follow :

builder.Services.AddDbContext<AppDbContext>();

builder.Services.AddControllers();

Then you call builder.Build() to create the WebApplication.

🛣 9. How does routing work in ASP.NET Core MVC?

Routing maps incoming URLs to controllers and actions.

ASP.NET Core uses Endpoint Routing to decide which route matches a request.

Example:

app.MapControllerRoute(

name: "default",

pattern: "{controller=Home}/{action=Index}/{id?}");

If the user visits /product/details/5, it maps to:

ProductController → Details(int id = 5).

🏷 10. Difference between Conventional and Attribute

Routing.

Type Definition Example

Conventional

Routing

Routes defined in

Program.cs or

Startup.cs.

{controller=Home}/{action=Ind

ex}/{id?}

Attribute

Routing

Routes defined with

attributes on controller

actions.

[Route("api/products/{id}")]

Example:

[Route("api/[controller]")]

Follow :

public class ProductsController : ControllerBase

[HttpGet("{id}")]

public IActionResult Get(int id) => Ok($"Product {id}");

🧩 11. What is Endpoint Routing?

Endpoint routing separates route matching from execution.

It lets middleware (like authentication) know which endpoint will be executed before it

runs.

Example:

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints => endpoints.MapControllers());

🔄 12. Explain the role of middleware in ASP.NET Core.

Middleware are components that handle requests and responses in a pipeline. Each

can:

  • Process requests
  • Call the next middleware
  • Or short-circuit the pipeline

Example:

A logging middleware that runs before all others:

app.Use(async (context, next) =>

Console.WriteLine("Request: " + context.Request.Path);

Follow :

await next();

});

🕒 13. What is the order of middleware execution?

Middleware execute in the order they’re added in Program.cs.

Response flows in reverse order back up the chain.

Tip:

  • Authentication must come before Authorization.
  • UseRouting must come before UseEndpoints.

🧩 14. How to create custom middleware?

Example:

public class RequestLoggingMiddleware

private readonly RequestDelegate _next;

public RequestLoggingMiddleware(RequestDelegate next) => _next =

next;

public async Task Invoke(HttpContext context)

Console.WriteLine($"Request for: {context.Request.Path}");

await _next(context);

Register it:

app.UseMiddleware<RequestLoggingMiddleware>();

Follow :

🧱 15. What is the difference between middleware and

filters?

Feature Middleware Filter

Scope Entire app Controller/action level

Runs on Every request MVC actions only

Example Authentication, logging Validation, exception filters

⚒ 16. Explain the IApplicationBuilder interface.

IApplicationBuilder builds the middleware pipeline.

You use it in Startup.Configure() or Program.cs to add middleware via Use, Run,

and Map.

🔀 17. Difference between Use, Run, and Map in

middleware.

Metho

Description Example

Use Adds middleware that can call

the next component.

app.UseMiddleware<Logging>();

Run Terminates the pipeline — no

next middleware.

app.Run(async c => await

c.Response.WriteAsync("End"));

Map Branches pipeline based on

request path.

app.Map("/admin", a =>

a.Run(...));

Follow :

🏗 18. What are Hosting Models in ASP.NET Core

(In-process vs Out-of-process)?

Model Description Performance

In-process App runs inside IIS worker process

(w3wp.exe).

Faster (single

process)

Out-of-proces

IIS acts as reverse proxy to Kestrel. Slight overhead

Example:

For Windows servers, in-process gives best performance. For cross-platform Docker, use

out-of-process.

🌍 19. Explain Web Host vs Generic Host.

Host Type Used For Example

Web Host Web apps (ASP.NET Core ≤ 2.2) WebHost.CreateDefaultBui

lder()

Generic

Host

Any app: web, worker, console (≥ 3.0) Host.CreateDefaultBuilde

r()

Generic Host unifies background tasks, APIs, and services in one model.

⚙ 20. How does configuration binding work in

ASP.NET Core?

ASP.NET Core can automatically bind configuration from:

  • appsettings.json
  • Environment variables

Follow :

  • Command-line arguments

Example:

// appsettings.json

"AppSettings": {

"SiteName": "MyShop",

"Version": "1.0"

// POCO

public class AppSettings

public string SiteName { get; set; }

public string Version { get; set; }

// Program.cs

builder.Services.Configure<AppSettings>(

builder.Configuration.GetSection("AppSettings"));

You can inject IOptions<AppSettings> anywhere.

MVC Architecture & Controllers

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

builder.Services.AddStackExchangeRedisCache(options =>

options.Configuration = "localhost:6379";

});

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

dotnet publish -c Release -o C:\inetpub\wwwroot\MyApp

Permalink

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?

Follow :

ASP.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}");

Follow :

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:

appsettings.json

appsettings.Development.json

appsettings.Staging.json

appsettings.Production.json

Program.cs:

builder.Configuration

.AddJsonFile("appsettings.json")

.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.jso

n", optional: true);

At runtime, only the file matching the current environment will override base settings.

Example:

appsettings.json

{ "AppName": "MyApp", "LogLevel": "Information" }

appsettings.Production.json

{ "LogLevel": "Error" }

Follow :

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:

appsettings.json

"AppSettings": {

"SiteName": "TechStore",

"PageSize": 20,

"EnableCache": true

Create a POCO:

public class AppSettings

Follow :

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

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

[Authorize]

[ApiController]

[Route("api/[controller]")]

public class OrdersController : ControllerBase

[HttpGet]

Follow :

public IActionResult GetOrders() => Ok("Secured Orders");

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

public virtual Category Category { get; set; }

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

public class ApplicationUser : IdentityUser

public string FullName { get; set; }

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Follow :

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

TestContainers spins up real Docker containers (SQL Server, Redis) for integration

testing, simulating production.

Example:

using Testcontainers.MsSql;

var sqlContainer = new MsSqlBuilder()

.WithPassword("yourStrong(!)Password")

.Build();

await sqlContainer.StartAsync();

var options = new DbContextOptionsBuilder<AppDbContext>()

.UseSqlServer(sqlContainer.GetConnectionString())

.Options;

// Use context in tests

Follow :

✅ Benefits:

  • Real database behavior
  • CI/CD friendly
  • Close to production setup

Deployment & Hosting

How to Deploy an ASP.NET Core App to IIS?

IIS (Internet Information Services) can host ASP.NET Core apps via the ASP.NET Core

Module, which forwards requests to Kestrel.

Steps:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Application Insights provides monitoring, telemetry, and tracing.

Setup:

builder.Services.AddApplicationInsightsTelemetry(builder.Configurati

on["APPINSIGHTS_INSTRUMENTATIONKEY"]);

Features:

  • Track requests, exceptions, and dependencies
  • Live metrics and dashboards

Follow :

  • Custom events and telemetry

9⃣ How to Monitor Performance and Uptime?

Techniques:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

EF Core allows using InMemoryDatabase or mocking DbSet<T> to avoid hitting a real

database.

Example with InMemoryDatabase:

var options = new DbContextOptionsBuilder<AppDbContext>()

.UseInMemoryDatabase(databaseName: "TestDb")

.Options;

using var context = new AppDbContext(options);

context.Products.Add(new Product { Id = 1, Name = "Laptop" });

context.SaveChanges();

// Act

var service = new ProductService(context);

var products = service.GetAll();

// Assert

Assert.Single(products);

Example with Moq (for advanced mocking):

Follow :

var mockSet = new Mock<DbSet<Product>>();

var mockContext = new Mock<AppDbContext>();

mockContext.Setup(c => c.Products).Returns(mockSet.Object);

3⃣ What is Integration Testing in ASP.NET Core?

Integration tests test the application as a whole, including middleware, routing,

controllers, and database.

  • Ensures all parts work together.
  • Usually uses WebApplicationFactory for hosting the app in-memory.

Example:

public class ProductsApiTests :

IClassFixture<WebApplicationFactory<Program>>

private readonly HttpClient _client;

public ProductsApiTests(WebApplicationFactory<Program> factory)

_client = factory.CreateClient();

[Fact]

public async Task GetProducts_ReturnsOk()

var response = await _client.GetAsync("/api/products");

response.EnsureSuccessStatusCode();

var products = await

response.Content.ReadFromJsonAsync<List<Product>>();

Assert.NotNull(products);

Follow :

✅ Integration tests are slower but catch real runtime issues.

4⃣ How Do You Test Middleware?

Middleware can be tested by invoking it in isolation using RequestDelegate.

Example:

[Fact]

public async Task CustomMiddleware_SetsHeader()

// Arrange

var middleware = new CustomHeaderMiddleware(async

(innerHttpContext) =>

await innerHttpContext.Response.WriteAsync("Hello");

});

var context = new DefaultHttpContext();

// Act

await middleware.InvokeAsync(context);

// Assert

Assert.Equal("MyValue",

context.Response.Headers["X-Custom-Header"]);

✅ Test middleware without starting a real server.

5⃣ How to Use WebApplicationFactory for Testing?

Follow :

WebApplicationFactory<T> spins up your ASP.NET Core app in-memory, perfect for

integration tests or testing minimal APIs.

Example:

var factory = new WebApplicationFactory<Program>();

var client = factory.CreateClient();

var response = await client.GetAsync("/api/products");

response.EnsureSuccessStatusCode();

You can override services for testing:

var factory = new WebApplicationFactory<Program>()

.WithWebHostBuilder(builder =>

builder.ConfigureServices(services =>

services.AddDbContext<AppDbContext>(options =>

options.UseInMemoryDatabase("TestDb"));

});

});

6⃣ How to Test Minimal APIs?

Minimal APIs are tested using WebApplicationFactory or TestServer.

Example:

var factory = new WebApplicationFactory<Program>();

var client = factory.CreateClient();

var response = await client.GetAsync("/products");

var products = await

response.Content.ReadFromJsonAsync<List<Product>>();

Follow :

Assert.NotEmpty(products);

7⃣ What Frameworks Are Commonly Used?

  • xUnit – Popular, lightweight, supports parallel testing.
  • NUnit – Rich assertion library.
  • MSTest – Microsoft-supported, integrated in Visual Studio.

Most modern ASP.NET Core projects use xUnit + Moq.

8⃣ How to Use Moq for Mocking Dependencies?

Moq creates fake implementations of interfaces to control behavior during tests.

Example:

var mockRepo = new Mock<IProductRepository>();

mockRepo.Setup(x => x.GetAll()).Returns(new List<Product> { new

Product { Id = 1, Name = "Laptop" } });

var service = new ProductService(mockRepo.Object);

var products = service.GetAll();

Assert.Single(products);

✅ Use .Setup(), .Verify(), and .Returns() to simulate behavior.

9⃣ How to Use InMemoryDatabase for EF Core Testing?

Follow :

EF Core InMemoryDatabase allows quick tests without SQL Server.

Steps:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

builder.Services.AddHealthChecks();

app.MapHealthChecks("/health");

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Role-based authorization restricts access based on user roles.

Assign a role:

await _userManager.AddToRoleAsync(user, "Admin");

Use in controllers:

[Authorize(Roles = "Admin")]

public IActionResult Dashboard() => View();

You can also combine roles:

[Authorize(Roles = "Admin,Manager")]

🧭 7. What is policy-based authorization?

Policy-based authorization gives fine-grained control over access using custom rules.

Instead of just roles, you define policies with specific requirements.

Define a policy:

builder.Services.AddAuthorization(options =>

options.AddPolicy("RequireAdminEmail", policy =>

Follow :

policy.RequireClaim(ClaimTypes.Email, "admin@myapp.com"));

});

Apply policy:

[Authorize(Policy = "RequireAdminEmail")]

public IActionResult AdminOnly() => View();

⚖ 8. How to create custom authorization policies?

You can write custom authorization handlers to evaluate complex logic.

Example:

public class MinimumAgeRequirement : IAuthorizationRequirement

public int Age { get; }

public MinimumAgeRequirement(int age) => Age = age;

public class MinimumAgeHandler :

AuthorizationHandler<MinimumAgeRequirement>

protected override Task HandleRequirementAsync(

AuthorizationHandlerContext context, MinimumAgeRequirement

requirement)

var birthDateClaim = context.User.FindFirst(c => c.Type ==

"BirthDate");

if (birthDateClaim != null)

var birthDate = DateTime.Parse(birthDateClaim.Value);

if (birthDate.AddYears(requirement.Age) <=

DateTime.Today)

context.Succeed(requirement);

Follow :

return Task.CompletedTask;

Register it:

builder.Services.AddAuthorization(options =>

options.AddPolicy("AdultOnly", policy =>

policy.Requirements.Add(new MinimumAgeRequirement(18)));

});

builder.Services.AddSingleton<IAuthorizationHandler,

MinimumAgeHandler>();

Use it:

[Authorize(Policy = "AdultOnly")]

public IActionResult BuyAlcohol() => Ok("Access granted");

🍪 9. What is cookie authentication in ASP.NET Core?

Cookie authentication stores user information in an encrypted cookie on the browser.

When the user revisits, the cookie is used to identify them.

Configure:

builder.Services.AddAuthentication(CookieAuthenticationDefaults.Auth

enticationScheme)

.AddCookie(options =>

options.LoginPath = "/Account/Login";

options.ExpireTimeSpan = TimeSpan.FromMinutes(30);

});

Once the user logs in:

Follow :

await HttpContext.SignInAsync(

CookieAuthenticationDefaults.AuthenticationScheme,

new ClaimsPrincipal(identity));

🌐 10. How to integrate OAuth2 / OpenID Connect in

ASP.NET Core?

ASP.NET Core supports external providers like Google, Microsoft, Azure AD, etc. using

OAuth2 and OpenID Connect.

Example for OpenID Connect (Azure AD):

builder.Services.AddAuthentication(OpenIdConnectDefaults.Authenticat

ionScheme)

.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureA

d"));

appsettings.json:

"AzureAd": {

"ClientId": "your-client-id",

"TenantId": "your-tenant-id",

"Instance": "

"CallbackPath": "/signin-oidc"

This handles sign-in, token validation, and claims setup automatically.

🔐 11. How to implement Google or Azure AD login?

builder.Services.AddAuthentication()

Follow :

.AddGoogle(options =>

options.ClientId = builder.Configuration["Google:ClientId"];

options.ClientSecret =

builder.Configuration["Google:ClientSecret"];

});

For Azure AD:

builder.Services.AddAuthentication(OpenIdConnectDefaults.Authenticat

ionScheme)

.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureA

d"));

ASP.NET Core will redirect users to Google/Azure login and handle tokens automatically.

🧱 12. What is AuthorizeAttribute?

[Authorize] is an attribute that restricts access to actions or controllers.

Examples:

[Authorize] // Any logged-in user

[Authorize(Roles = "Admin")] // Only admins

[Authorize(Policy = "AdultOnly")] // Custom policy

You can also allow anonymous access:

[AllowAnonymous]

public IActionResult Login() => View();

🧭 13. How to protect specific actions or controllers?

Follow :

Apply [Authorize] at different levels:

Controller-level:

[Authorize]

public class OrdersController : Controller { ... }

Action-level:

[Authorize(Roles = "Manager")]

public IActionResult ApproveOrder() => View();

⚙ 14. What are authentication schemes?

An authentication scheme defines how users are authenticated — via cookies, JWT,

Google, etc.

Each scheme has:

  • A name
  • A handler (e.g., JWT handler, cookie handler)

Example:

builder.Services.AddAuthentication()

.AddCookie("Cookies")

.AddJwtBearer("Jwt", options => { ... });

You can specify the scheme explicitly:

[Authorize(AuthenticationSchemes = "Jwt")]

🔄 15. How to use multiple authentication handlers?

Follow :

You can configure multiple schemes and choose dynamically per endpoint.

Example:

builder.Services.AddAuthentication(options =>

options.DefaultAuthenticateScheme = "JwtOrCookie";

.AddPolicyScheme("JwtOrCookie", "JWT or Cookie", options =>

options.ForwardDefaultSelector = context =>

context.Request.Headers.ContainsKey("Authorization") ? "Jwt"

: "Cookies";

.AddCookie("Cookies")

.AddJwtBearer("Jwt", options => { ... });

This setup allows both cookie-based (web) and JWT (API) authentication in the same app.

✅ Summary:

  • ASP.NET Core Identity manages users and roles.
  • Claims-based authentication represents user info flexibly.
  • JWT enables stateless API security.
  • Policies allow custom rules beyond roles.
  • Schemes let you combine multiple authentication systems (cookies, JWT, Google).

Configuration & Environments

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Claims-based authentication is based on claims — pieces of information about the user

(like email, role, or permissions).

Each user has a collection of claims represented as key-value pairs.

Example:

new Claim(ClaimTypes.Email, "user@example.com");

new Claim(ClaimTypes.Role, "Admin");

When a user logs in, these claims are stored in their authentication token or cookie — used

later for authorization.

🔑 4. What are JWT tokens?

JWT (JSON Web Token) is a compact, URL-safe token used for stateless authentication in

APIs.

A JWT contains three parts:

Header.Payload.Signature

Example Payload:

"sub": "user123",

"email": "user@example.com",

"role": "Admin",

"exp": 1735196400

It’s signed (usually with HMAC-SHA256) so that the server can verify it hasn’t been

tampered with.

Follow :

🔒 5. How do you secure an API using JWT?

Install package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Value converters transform data between your entity property and database column type.

Example:

Store an enum as a string in the DB:

modelBuilder.Entity<User>()

.Property(u => u.Status)

.HasConversion<string>();

Or encrypt/decrypt sensitive data:

.Property(p => p.SSN)

.HasConversion(

v => Encrypt(v), // to DB

v => Decrypt(v)); // from DB

🔍 9. What is the Change Tracker?

The Change Tracker keeps track of all entity states (Added, Modified, Deleted,

Unchanged) in a DbContext session.

Example:

var product = _context.Products.Find(1);

product.Price = 1500;

var entries = _context.ChangeTracker.Entries();

foreach (var entry in entries)

Console.WriteLine($"{entry.Entity.GetType().Name} -

{entry.State}");

Follow :

When you call _context.SaveChanges(), EF Core generates the required SQL

automatically.

🔐 10. How does EF Core handle concurrency?

EF Core uses optimistic concurrency — multiple users can edit the same data, but if one

user saves after another, a DbUpdateConcurrencyException occurs.

Example:

Add a concurrency token:

public class Product

public int Id { get; set; }

public string Name { get; set; }

[Timestamp]

public byte[] RowVersion { get; set; }

EF Core will include RowVersion in the WHERE clause to detect conflicts.

💳 11. How to use transactions in EF Core?

You can use:

using var transaction = _context.Database.BeginTransaction();

try

_context.Add(new Product { Name = "Book" });

_context.SaveChanges();

_context.Add(new Order { ProductId = 1 });

_context.SaveChanges();

Follow :

transaction.Commit();

catch

transaction.Rollback();

Or rely on EF Core’s automatic transaction within a single SaveChanges().

⚡ 12. How do you execute raw SQL in EF Core?

For performance tuning or advanced queries:

var products = _context.Products

.FromSqlRaw("SELECT * FROM Products WHERE Price > 1000")

.ToList();

For non-query operations:

_context.Database.ExecuteSqlRaw("UPDATE Products SET Price = Price *

1.1");

You can also use interpolated strings safely:

.FromSqlInterpolated($"SELECT * FROM Products WHERE Name = {name}");

🕵 13. What are Shadow Properties?

Shadow properties exist in the model but not in your C# class — EF Core creates them

automatically (like CreatedDate or UpdatedBy).

Example:

Follow :

modelBuilder.Entity<Product>()

.Property<DateTime>("CreatedOn")

.HasDefaultValueSql("GETDATE()");

You can access them via the Change Tracker:

var createdOn =

context.Entry(product).Property("CreatedOn").CurrentValue;

🧱 14. What is DbSet<T>?

A DbSet<T> represents a table in the database and provides an API for querying and

saving instances.

Example:

public class AppDbContext : DbContext

public DbSet<Product> Products { get; set; }

Usage:

var allProducts = _context.Products.ToList();

🌱 15. How to seed data in EF Core?

You can seed data via the Fluent API in OnModelCreating.

Example:

modelBuilder.Entity<Category>().HasData(

new Category { Id = 1, Name = "Electronics" },

new Category { Id = 2, Name = "Books" }

Follow :

Then run:

dotnet ef migrations add SeedData

dotnet ef database update

🚀 16. What’s new in EF Core 7/8?

Highlights:

  • Bulk updates/deletes:

_context.Products.Where(...).ExecuteUpdateAsync()

  • JSON column mapping (EF 7+)
  • Improved raw SQL mapping
  • Better performance in LINQ translation
  • TPH/TPM inheritance enhancements
  • Auto compile query caching
  • TimeOnly/DateOnly support (EF 8)

EF Core 8 is optimized for .NET 8 and cloud-native apps.

⚙ 17. How do you optimize EF Core performance?

Best Practices:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Partial views are used to render reusable page sections (like headers, sidebars).

Example:

public IActionResult ProductList()

var products = _service.GetAll();

return PartialView("_ProductListPartial", products);

In Razor:

Follow :

@Html.Partial("_ProductListPartial", Model.Products)

🧾 20. Explain Razor Pages vs MVC.

Feature Razor Pages MVC

Structure Page-based (.cshtml +

.cshtml.cs)

Controller + View

Best For Simple or CRUD pages Complex or large web apps

URL /Products/Edit →

/Pages/Products/Edit.cshtml

/Products/Edit →

ProductController.Edit()

Code

Location

In the same file (PageModel) Separate Controller class

Example:

Razor Pages are like simplified MVC without controllers — great for admin dashboards or

forms.

Dependency Injection (DI)

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Logging in production should be:

  • Centralized
  • Structured
  • Persistent
  • Low-overhead

ASP.NET Core has ILogger interface and supports logging providers like Console, File,

Seq, Application Insights.

Example:

public class HomeController : Controller

private readonly ILogger<HomeController> _logger;

public HomeController(ILogger<HomeController> logger) => _logger

= logger;

Follow :

public IActionResult Index()

_logger.LogInformation("Index page visited at {Time}",

DateTime.UtcNow);

return View();

6⃣ What is Structured Logging?

Structured logging stores log data as key-value pairs instead of plain text.

Allows querying, filtering, and dashboards.

Example with Serilog:

Log.Logger = new LoggerConfiguration()

.Enrich.FromLogContext()

.WriteTo.Console()

.WriteTo.File("logs/log-.txt", rollingInterval:

RollingInterval.Day)

.CreateLogger();

Log Output:

"Timestamp": "2025-10-28T12:00:00Z",

"Level": "Information",

"Message": "Index page visited",

"Time": "2025-10-28T12:00:00Z"

✅ Makes filtering by user, requestId, or error type very easy.

7⃣ How to Use Serilog or NLog?

Follow :

Serilog Example (Program.cs):

builder.Host.UseSerilog((ctx, lc) => lc

.WriteTo.Console()

.WriteTo.File("logs/log-.txt", rollingInterval:

RollingInterval.Day)

NLog Example:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

In-memory caching stores data in the memory of the application server.

It’s fast, but data is lost if the app restarts or scales across multiple servers.

Setup:

builder.Services.AddMemoryCache();

Usage:

_cache.Set("key", value, TimeSpan.FromMinutes(10));

var data = _cache.Get("key");

✅ Ideal for single-server apps or short-term caching (e.g., reference data, dropdown lists).

❌ Not suitable for load-balanced environments.

🌐 3. What is Distributed Caching?

Distributed caching stores data in an external cache server (e.g., Redis, SQL Server), so

all app instances share the same cache.

Setup:

builder.Services.AddStackExchangeRedisCache(options =>

Follow :

options.Configuration = "localhost:6379";

options.InstanceName = "MyApp_";

});

Usage:

public class CacheService

private readonly IDistributedCache _cache;

public CacheService(IDistributedCache cache) => _cache = cache;

public async Task<string> GetCachedDataAsync()

var data = await _cache.GetStringAsync("welcome");

if (data == null)

data = "Hello, from Redis!";

await _cache.SetStringAsync("welcome", data,

new DistributedCacheEntryOptions

AbsoluteExpirationRelativeToNow =

TimeSpan.FromMinutes(10)

});

return data;

✅ Great for cloud, containerized, or multi-server setups.

🧠 4. How do you use Redis caching?

Redis is a fast, in-memory, key-value data store used for distributed caching.

Follow :

Steps:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

You can use:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Response caching caches the entire HTTP response at the server level — useful for

static or rarely changing API responses.

Setup:

builder.Services.AddResponseCaching();

var app = builder.Build();

app.UseResponseCaching();

Controller Example:

[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any)]

Follow :

[HttpGet]

public IActionResult GetTime() => Ok(DateTime.Now);

✅ The response is cached for 60 seconds — subsequent requests are served faster.

Make sure to set appropriate cache headers in the response.

🚀 6. What is Output Caching in .NET 8?

Output caching (introduced in .NET 8) is an advanced version of response caching that

stores rendered outputs at the middleware level — and supports vary-by, policies, and

authorization.

Setup:

builder.Services.AddOutputCache();

var app = builder.Build();

app.UseOutputCache();

Usage:

[OutputCache(Duration = 60, VaryByQueryKeys = new[] { "category" })]

[HttpGet]

public IActionResult GetProducts(string category)

return Ok(new { Category = category, Time = DateTime.Now });

✅ Benefits:

  • Works with authenticated users.
  • Supports vary-by parameters, headers, and policies.
  • Integrates well with minimal APIs and Razor pages.

Follow :

🗜 7. How to compress responses?

Use response compression middleware to reduce payload size for clients.

Setup:

builder.Services.AddResponseCompression(options =>

options.EnableForHttps = true;

options.Providers.Add<GzipCompressionProvider>();

});

builder.Services.Configure<GzipCompressionProviderOptions>(opt =>

opt.Level = CompressionLevel.Fastest);

var app = builder.Build();

app.UseResponseCompression();

✅ Compresses responses using Gzip or Brotli automatically.

Common for APIs serving large JSON or text content.

⚙ 8. What is async/await and why is it important in

web apps?

async/await enables non-blocking I/O operations, allowing your web server to handle

thousands of concurrent requests efficiently.

Example:

[HttpGet]

public async Task<IActionResult> GetData()

var data = await _service.GetDataAsync(); // Non-blocking call

return Ok(data);

Follow :

✅ Benefits:

  • Frees threads while waiting for I/O (e.g., DB, HTTP calls).
  • Improves scalability and throughput.
  • Essential for high-traffic APIs and cloud-native apps.

❌ Avoid Task.Result or .Wait() — they block threads and reduce performance.

⚡ 9. How to optimize startup performance?

To improve startup and cold-boot performance:

✅ Tips:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

ASP.NET Core handles HTTP requests through a middleware pipeline, which is a

sequence of components where each can:

  • Inspect or modify the request
  • Call the next middleware
  • Short-circuit the pipeline

Pipeline Flow:

Request -> Middleware1 -> Middleware2 -> Middleware3 -> Endpoint ->

Response back

Example:

app.Use(async (context, next) =>

Console.WriteLine("Before Middleware 1");

await next();

Console.WriteLine("After Middleware 1");

});

app.Use(async (context, next) =>

Console.WriteLine("Middleware 2");

Follow :

await next();

});

app.Run(async context =>

await context.Response.WriteAsync("Hello World");

});

Key Points:

  • Order matters!
  • Use → can call next middleware
  • Run → terminates pipeline (no next)
  • Map → conditionally routes requests

2⃣ How ASP.NET Core Handles gRPC

  • gRPC uses HTTP/2, binary serialization (Protobuf), and strongly typed contracts.
  • Add gRPC service:

builder.Services.AddGrpc();

app.MapGrpcService<MyGrpcService>();

  • Clients can call server methods over HTTP/2 for high-performance RPC.

Use Cases: Microservices, real-time streaming, low-latency APIs.

3⃣ SignalR vs WebSockets

Follow :

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.

4⃣ Using SignalR for Real-Time Communication

// Hub

public class ChatHub : Hub

public async Task SendMessage(string user, string message) =>

await Clients.All.SendAsync("ReceiveMessage", user,

message);

// Client (JavaScript)

const connection = new signalR.HubConnectionBuilder()

.withUrl("/chathub")

.build();

connection.on("ReceiveMessage", (user, message) => {

console.log(`${user}: ${message}`);

});

await connection.start();

await connection.invoke("SendMessage", "Alice", "Hello!");

5⃣ Background Services (IHostedService)

Follow :

  • For long-running tasks or scheduled jobs
  • Implement IHostedService or extend BackgroundService

public class TimedWorker : BackgroundService

protected override async Task ExecuteAsync(CancellationToken

stoppingToken)

while (!stoppingToken.IsCancellationRequested)

Console.WriteLine("Running background task");

await Task.Delay(10000, stoppingToken);

builder.Services.AddHostedService<TimedWorker>();

✅ Good for periodic jobs, email processing, queue consumers.

6⃣ Hangfire or Quartz.NET for Background Jobs

Hangfire Example:

app.UseHangfireDashboard();

RecurringJob.AddOrUpdate(() => Console.WriteLine("Recurring job"),

Cron.Daily);

Quartz.NET: Supports cron-like scheduling and clustered execution.

7⃣ Health Checking in ASP.NET Core

builder.Services.AddHealthChecks()

.AddSqlServer(connectionString)

.AddCheck<CustomHealthCheck>("CustomCheck");

Follow :

app.MapHealthChecks("/health");

Custom Health Check Example:

public class CustomHealthCheck : IHealthCheck

public Task<HealthCheckResult>

CheckHealthAsync(HealthCheckContext context, CancellationToken

token) =>

Task.FromResult(HealthCheckResult.Healthy("Everything OK"));

8⃣ Rate Limiting Middleware in .NET 8

builder.Services.AddRateLimiter(options =>

options.GlobalLimiter =

PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>

RateLimitPartition.GetFixedWindowLimiter(httpContext.Connection.Remo

teIpAddress?.ToString()!, _ =>

new FixedWindowRateLimiterOptions

PermitLimit = 10,

Window = TimeSpan.FromMinutes(1),

QueueLimit = 2

}));

});

app.UseRateLimiter();

✅ Helps protect APIs from abuse or DoS attacks.

Follow :

9⃣ DataAnnotations for Validation

public class Product

[Required]

public string Name { get; set; }

[Range(1, 100)]

public decimal Price { get; set; }

  • Works with model binding
  • Automatic client & server-side validation with Razor or API endpoints

🔟 Global Exception Logging

app.UseExceptionHandler(errorApp =>

errorApp.Run(async context =>

var error =

context.Features.Get<IExceptionHandlerPathFeature>();

Log.Error(error.Error, "Unhandled exception");

context.Response.StatusCode = 500;

await context.Response.WriteAsync("An error occurred");

});

});

1⃣1⃣ Anti-Forgery Tokens

  • Protects against CSRF attacks
  • In Razor:

Follow :

<form method="post">

@Html.AntiForgeryToken()

</form>

  • In API: use services.AddAntiforgery(), validate via

[ValidateAntiForgeryToken].

1⃣2⃣ 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⃣3⃣ DI vs Service Locator

  • Dependency Injection: Dependencies are injected via constructor or method.

Promotes loose coupling.

  • Service Locator: Class fetches dependencies from a central registry. Leads to

hidden dependencies, harder to test.

✅ DI is the preferred modern pattern.

Performance Tuning Best Practices

  • Use async/await for I/O bound tasks
  • Use response caching & output caching

Follow :

  • Minimize middleware overhead
  • Use compiled queries for EF Core
  • Enable gzip compression
  • Use object pooling for high-load scenarios

Localization & Globalization

builder.Services.AddLocalization(options => options.ResourcesPath =

"Resources");

var supportedCultures = new[] { "en-US", "fr-FR" };

app.UseRequestLocalization(new RequestLocalizationOptions

DefaultRequestCulture = new RequestCulture("en-US"),

SupportedCultures = supportedCultures,

SupportedUICultures = supportedCultures

});

✅ Allows apps to support multiple languages & regions.

Output & Input Formatters

  • Input Formatters: Deserialize request body (JSON, XML, Protobuf)
  • Output Formatters: Serialize response

builder.Services.AddControllers()

.AddJsonOptions(opt =>

opt.JsonSerializerOptions.PropertyNamingPolicy = null)

.AddXmlSerializerFormatters();

Follow :

Integrating GraphQL

builder.Services.AddGraphQLServer()

.AddQueryType<Query>();

app.MapGraphQL();

  • Query APIs flexibly, single endpoint
  • Better for nested object queries vs REST

Common Pitfalls Migrating from MVC 5 to ASP.NET

Core MVC

  • Global.asax → Program.cs & Startup.cs
  • Web.config → appsettings.json
  • HttpContext.Items, Session handling differs
  • Filter pipeline changed
  • Dependency injection built-in (no manual factories)
  • Authentication/Authorization model changed (Claims-based by default)
  • No System.Web; libraries must be compatible

Follow :

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Docker allows running ASP.NET Core apps in containers, portable across environments.

Dockerfile Example:

# Build stage

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build

WORKDIR /app

COPY *.csproj ./

RUN dotnet restore

COPY . ./

RUN dotnet publish -c Release -o out

# Runtime stage

FROM mcr.microsoft.com/dotnet/aspnet:8.0

WORKDIR /app

COPY --from=build /app/out .

ENTRYPOINT ["dotnet", "MyApp.dll"]

Build & Run:

docker build -t myapp:latest .

docker run -d -p 8080:80 myapp:latest

✅ Benefits:

  • Environment-independent
  • Easy scaling in Kubernetes or cloud
  • Versioning via images

3⃣ How to Host in Azure App Service?

Follow :

Azure App Service provides PaaS hosting for ASP.NET Core apps.

Steps:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Configuration providers are components that load configuration data from various

sources.

Built-in Providers:

  • JSON files (appsettings.json)
  • Environment variables
  • Command-line arguments

Follow :

  • In-memory collections
  • Azure Key Vault
  • User Secrets (for local dev)
  • Custom providers (you can build your own)

Example:

builder.Configuration

.AddJsonFile("appsettings.json")

.AddEnvironmentVariables()

.AddCommandLine(args);

Each provider plugs into the same configuration system, so you can access everything via

IConfiguration.

🔐 3. How do you manage secrets in development?

In development, never store passwords, API keys, or connection strings in code or

appsettings.json.

Use User Secrets — a safe way to store secrets outside the project tree.

🧰 4. What is User Secrets in ASP.NET Core?

User Secrets are a local, developer-only configuration storage that keeps sensitive data

out of source control.

Setup:

Enable secrets:

dotnet user-secrets init

Follow :

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

public class LogActionFilter : ActionFilterAttribute

public override void OnActionExecuting(ActionExecutingContext

context)

Console.WriteLine($"Action:

{context.ActionDescriptor.DisplayName}");

Use it:

[LogActionFilter]

public IActionResult Index() => View();

📤 15. How do you pass data from controller to view?

You can use:

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Review the concept and prepare a concise verbal explanation with a real project example.

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

Compiled queries improve performance by caching query translation.

Example:

private static readonly Func<AppDbContext, decimal,

IEnumerable<Product>> _getExpensiveProducts =

EF.CompileQuery((AppDbContext ctx, decimal price) =>

ctx.Products.Where(p => p.Price > price));

var result = _getExpensiveProducts(_context, 1000);

🔍 19. What is global query filtering?

It allows you to apply filters automatically to all queries for a given entity — useful for soft

deletes or multi-tenancy.

Example:

Follow :

modelBuilder.Entity<Product>()

.HasQueryFilter(p => !p.IsDeleted);

All queries automatically exclude deleted products.

🌐 20. How do you handle database connection

pooling?

Connection pooling is handled automatically by ADO.NET and EF Core providers.

Each new DbContext reuses existing connections from the pool to reduce overhead.

For fine control:

options.UseSqlServer(connectionString, opt =>

opt.EnableRetryOnFailure());

Tips:

  • Keep DbContexts short-lived (Scoped lifetime).
  • Avoid keeping connections open unnecessarily.

Follow :

  • For high-traffic apps, tune pool

settings in the connection string:

Max Pool Size=200; Min

Pool Size=5;

Authentication & Authorization

Permalink

ASP.NET Core MVC ASP.NET Core MVC Tutorial · MVC

ASP.NET Core Data Protection API provides secure cryptographic APIs for:

  • Encrypting cookies and tokens
  • Protecting form data
  • Persisting secure keys (across app restarts)

Setup:

builder.Services.AddDataProtection()

.PersistKeysToFileSystem(new DirectoryInfo(@"c:\keys"))

.SetApplicationName("MyApp");

You can use it directly:

var protector = _provider.CreateProtector("MyPurpose");

var encrypted = protector.Protect("secret-data");

var decrypted = protector.Unprotect(encrypted);

✅ Data Protection is the backbone for:

  • Cookie Authentication
  • CSRF Tokens
  • TempData encryption

🧠 Summary

Concept Description Best For

In-memory caching Stores data in server memory Single-server or dev

Distributed caching Shared cache (Redis, SQL) Scalable apps

Response caching Caches HTTP responses Public/static data

Follow :

Output caching (.NET 8) Advanced, user-aware

caching

Dynamic APIs

Response compression Gzip/Brotli for responses Large payloads

Async/await Non-blocking I/O High concurrency

Startup optimization Faster app boot Cloud apps

Data protection Encrypt sensitive data Cookies, tokens,

forms

Testing

How to Unit Test Controllers?

Unit testing controllers ensures your business logic in action methods works correctly

without hitting the database or HTTP pipeline.

Steps:

Permalink