Interview Q&A

Master technical and career interviews with structured answers—short definition, real examples, pitfalls, and how to answer in 60–90 seconds.

4616 total questions 4516 technical 100 career & HR 4346 from PDF library

Showing 1–8 of 8

Popular tracks

Junior PDF
What is ASP.NET Core, and how is it different from

SP.NET MVC 5? ASP.NET Core is a cross-platform, open-source framework for building modern web pplications, APIs, and microservices. It’s a complete rewrite of the old ASP.NET framework, designed to be lightweight, modula…

Junior PDF
What is EF Core?

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 manual…

Junior PDF
What is ASP.NET Core, and how is it different from ASP.NET MVC 5?

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-…

Junior PDF
This integrates Identity with EF Core using the AspNetUsers, AspNetRoles, etc. tables. 🧾 3. What is claims-based authentication?

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…

Junior PDF
This integrates Identity with EF Core using the AspNetUsers, AspNetRoles, etc. tables. 🧾 3. What is claims-based authentication? Follow :

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…

Junior PDF
Output caching (new in .NET 8) → Server-side output reuse. Example: builder.Services.AddMemoryCache(); public class ProductService { private readonly IMemoryCache _cache; public ProductService(IMemoryCache cache) => _cache = cache; public IEnumerable<Product> GetProducts() { if (!_cache.TryGetValue("products", out IEnumerable<Product> products)) { products = FetchFromDatabase(); Follow : _cache.Set("products", products, TimeSpan.FromMinutes(5)); } return products; } } ✅ Reduces DB load and speeds up response times. 💾 2. What is In-Memory Caching?

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",…

Junior PDF
Deploy self-contained trimmed builds for smaller binaries. Example for build optimization: dotnet publish -c Release /p:PublishTrimmed=true /p:ReadyToRun=true 🔐 10. What is Data Protection in ASP.NET Core?

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() .Persis…

Junior PDF
Deploy self-contained trimmed builds for smaller binaries. Example for build optimization: dotnet publish -c Release /p:PublishTrimmed=true /p:ReadyToRun=true 🔐 10. What is Data Protection in ASP.NET Core? Follow :

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() .Persis…

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

SP.NET MVC 5?

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

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

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

Example:

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

you add them in Program.cs.

pp.UseStaticFiles();

pp.UseRouting();

pp.UseAuthentication();

pp.UseAuthorization();

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

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

nd 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)
{

pp.UseRouting();

pp.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();

pp.MapControllers();

pp.Run();

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

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

ttributes. Perfect for microservices.

Example:

var app = WebApplication.Create(args);
pp.MapGet("/hello", () => "Hello World!");

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

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.

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

Example:

pp.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?}

ttribute

Routing

Routes defined with

ttributes on controller

ctions.

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

Example:

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

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:

pp.UseRouting();

pp.UseAuthorization();

pp.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:

logging middleware that runs before all others:

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

{

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

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

wait _next(context);

}
}

Register it:

pp.UseMiddleware<RequestLoggingMiddleware>();

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

nd Map.

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

middleware.

Metho

Description Example

Use Adds middleware that can call

the next component.

pp.UseMiddleware<Logging>();

Run Terminates the pipeline — no

next middleware.

pp.Run(async c => await

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

Map Branches pipeline based on

request path.

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

.Run(...));

🏗 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

ny 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

SP.NET Core?

ASP.NET Core can automatically bind configuration from:

  • appsettings.json
  • Environment variables
  • 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 & share

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

6?

Feature EF 6 EF Core

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

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

ppDbContext class:

public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) :

base(options) { }

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

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

💤 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 & share

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 & share

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

PIs.

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.

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

Install package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Permalink & share

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 & share

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 & share

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

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

caching

Dynamic APIs

Response compression Gzip/Brotli for responses Large payloads

sync/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 & share

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 & share
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details