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 26–50 of 53

Popular tracks

Mid PDF
Health Checks – Endpoint /health for app readiness builder.Services.AddHealthChecks();?

pp.MapHealthChecks("/health"); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not use it in product…

Mid PDF
Now, only requests with a valid JWT in the Authorization: Bearer <token> header can access it. 󰰣 6. Explain role-based authorization.

Role-based authorization restricts access based on user roles. ssign a role: wait _userManager.AddToRoleAsync(user, "Admin"); Use in controllers: [Authorize(Roles = "Admin")] public IActionResult Dashboard() =&gt; View()…

Mid PDF
DeveloperExceptionPage (for development) Example:?

pp.UseExceptionHandler("/Home/Error"); or public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { context.Result = new ViewResult { ViewName = "Error" }; } } 🧩 19. How…

Mid PDF
Health Checks – Endpoint /health for app readiness?

builder.Services.AddHealthChecks(); app.MapHealthChecks("/health"); What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you…

Mid PDF
Configure in Program.cs: builder.Logging.ClearProviders(); builder.Logging.SetMinimumLevel(LogLevel.Information); builder.Host.UseNLog(); ✅ Both support structured logging, sinks, filtering, and rolling files. 8⃣ How to Enable Application Insights?

Application Insights provides monitoring, telemetry, and tracing. Setup: builder.Services.AddApplicationInsightsTelemetry(builder.Configurati on["APPINSIGHTS_INSTRUMENTATIONKEY"]); Features: Track requests, exceptions, a…

Mid PDF
Run tests. Example: (covered earlier in Mock DbContext) ✅ Fast, reliable for unit or light integration tests, but not suitable for relational behaviors (like joins, transactions). 🔟 How Do You Implement TestContainers for Integration Testing?

TestContainers spins up real Docker containers (SQL Server, Redis) for integration testing, simulating production. Example: using Testcontainers.MsSql; var sqlContainer = new MsSqlBuilder() .WithPassword("yourStrong(!)Pa…

Mid PDF
Assert the result. Example: public class ProductsControllerTests { [Fact] public void Get_ReturnsOkResult_WithProducts() { // Arrange var mockService = new Mock<IProductService>(); mockService.Setup(s => s.GetAll()).Returns(new List<Product> { new Product { Id = 1, Name = "Laptop" } }); var controller = new ProductsController(mockService.Object); Follow : // Act var result = controller.Get(); // Assert var okResult = Assert.IsType<OkObjectResult>(result); var products = Assert.IsType<List<Product>>(okResult.Value); Assert.Single(products); } } ✅ Key: Mock all dependencies so controller is tested in isolation. 2⃣ How to Mock DbContext for Testing?

EF Core allows using InMemoryDatabase or mocking DbSet&lt;T&gt; to avoid hitting a real database. Example with InMemoryDatabase: var options = new DbContextOptionsBuilder&lt;AppDbContext&gt;() .UseInMemoryDatabase(databa…

Mid PDF
⚠ Use cautiously — lazy loading can cause performance issues (N+1 queries). 🚀 7. Difference between Eager, Lazy, and Explicit Loading. Type Description Example Eager Loading Load related data with the main query _context.Products.Include(p => p.Category) Lazy Loading Load data automatically when accessed product.Category.Name (auto fetches) Explicit Loading Manually load data later _context.Entry(product).Reference(p => p.Category).Load() Follow : Best practice: Use Eager loading for known data needs — more predictable and efficient. 🔄 8. What are Value Converters in EF Core?

Value converters transform data between your entity property and database column type. Example: Store an enum as a string in the DB: modelBuilder.Entity&lt;User&gt;() .Property(u =&gt; u.Status) .HasConversion&lt;string&…

Mid PDF
DeveloperExceptionPage (for development) Example: app.UseExceptionHandler("/Home/Error"); or public class GlobalExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { context.Result = new ViewResult { ViewName = "Error" }; } } 🧩 19. How to return partial views?

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

Mid PDF
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!");

Using SignalR for Real-Time Communication // Hub public class ChatHub : Hub { public async Task SendMessage(string user, string message) =&gt; await Clients.All.SendAsync("ReceiveMessage", user, message); } // Client (Ja…

Mid PDF
App Service automatically configures Kestrel + reverse proxy. ✅ Supports scaling, HTTPS, and monitoring out-of-the-box. 4⃣ How to Configure CI/CD Pipelines? Example with GitHub Actions: name: .NET Build & Deploy on: push: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup .NET uses: actions/setup-dotnet@v3 with: dotnet-version: '8.0.x' - name: Restore dependencies run: dotnet restore Follow : - name: Build run: dotnet build --configuration Release - name: Publish run: dotnet publish -c Release -o publish - name: Deploy to Azure uses: azure/webapps-deploy@v2 with: app-name: 'myapp' publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }} package: ./publish ✅ Ensures automatic builds, tests, and deployment on code changes. 5⃣ How to Log in Production?

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

Mid PDF
TempData – Stores data between redirects Example: Follow : ViewBag.Title = "Product List"; ViewData["Message"] = "Welcome!"; TempData["Alert"] = "Product saved!"; return View(products); 🧺 16. What are ViewBag, ViewData, and TempData? Type Lifetime Type Safety Use Case ViewBag Only current request Dynamic Small data to view ViewData Only current request Key-based Same as ViewBag TempData Survives redirect Key-based Pass data between requests ⚖ 17. Difference between ViewBag and TempData. Feature ViewBag TempData Lifetime Current request only Survives redirect Type Dynamic property Dictionary (object) Common Use Pass title or message Pass success/error alerts between pages Example: TempData["Success"] = "Product saved!"; return RedirectToAction("Index"); ⚠ 18. How to handle exceptions globally in ASP.NET Core MVC? Follow :

You can use: What interviewers expect A clear definition tied to MVC in ASP.NET Core MVC projects Trade-offs (performance, maintainability, security, cost) When you would and would not use it in production Real-world exa…

Mid PDF
Alerts – Email/SMS/Slack for failures or slow responses ✅ Helps detect issues before users notice. 🧠 Summary Table Topic Tool / Feature Notes IIS Deployment ASP.NET Core Hosting Bundle IIS acts as reverse proxy Docker Deployment Dockerfile Build + runtime stages

zure App Service PaaS Easy scaling, HTTPS CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy Logging ILogger, Serilog, NLog Use structured logging Monitoring Application Insights, Prometheus Track metrics, u…

Mid PDF
Configure web.config (generated automatically) to forward requests to Kestrel. web.config Example: <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" /> ✅ IIS acts as a reverse proxy, Kestrel handles HTTP requests. 2⃣ How to Deploy to Docker?

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…

Mid PDF
Exception (special case — when an error occurs) Tip: Filters with a lower Order value run first. Example: [MyActionFilter(Order = 1)] [MyLoggingFilter(Order = 2)] ⚒ 14. How do you create a custom action filter?

public class LogActionFilter : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); } } Use it: [LogAction…

Mid PDF
Alerts – Email/SMS/Slack for failures or slow responses ✅ Helps detect issues before users notice. 🧠 Summary Table Topic Tool / Feature Notes IIS Deployment ASP.NET Core Hosting Bundle IIS acts as reverse proxy Docker Deployment Dockerfile Build + runtime stages Azure App Service PaaS Easy scaling, HTTPS CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy Logging ILogger, Serilog, NLog Use structured logging Monitoring Application Insights, Prometheus Track metrics, uptime Follow : Health Checks ASP.NET Core HealthChecks Expose /health endpoints This gives a complete production-ready workflow from deployment to monitoring. Advanced & Modern Topics Middleware Pipeline in Depth?

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…

Mid PDF
Configure web.config (generated automatically) to forward requests to Kestrel. web.config Example: <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" /> ✅ IIS acts as a reverse proxy, Kestrel handles HTTP requests. Follow : 2⃣ How to Deploy to Docker?

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…

Mid PDF
User secrets (in Development) These are merged in order — later values override earlier ones. 🧱 2. What are configuration providers?

Configuration providers are components that load configuration data from various sources. Built-in Providers: JSON files (appsettings.json) Environment variables Command-line arguments In-memory collections Azure Key Vau…

Mid PDF
Exception (special case — when an error occurs) Tip: Filters with a lower Order value run first. Example: Follow : [MyActionFilter(Order = 1)] [MyLoggingFilter(Order = 2)] ⚒ 14. How do you create a custom action filter?

public class LogActionFilter : ActionFilterAttribute public override void OnActionExecuting(ActionExecutingContext context) Console.WriteLine($"Action: {context.ActionDescriptor.DisplayName}"); Use it: [LogActionFilter]…

Mid PDF
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.

Answer: Hangfire or Quartz.NET for Background Jobs Hangfire Example: app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() =&amp;gt; Console.WriteLine("Recurring job"), Cron.Daily); Quartz.NET: Supports cron-like sched…

Mid PDF
How to Test Minimal APIs? Answer: 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>>(); Assert.NotEmpty(products);

How to Test Minimal APIs? Answer: Minimal APIs are tested using WebApplicationFactory or TestServer. Example: var factory = new WebApplicationFactory&lt;Program&gt;(); var client = factory.CreateClient(); var response =…

Mid PDF
Health Checking in ASP.NET Core builder.Services.AddHealthChecks() .AddSqlServer(connectionString) .AddCheck<CustomHealthCheck>("CustomCheck"); 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")); }

Health Checking in ASP.NET Core builder.Services.AddHealthChecks() .AddSqlServer(connectionString) .AddCheck&lt;CustomHealthCheck&gt;("CustomCheck"); app.MapHealthChecks("/health"); Custom Health Check Example: public cl…

Mid PDF
How to Use Serilog or NLog? Serilog Example (Program.cs): builder.Host.UseSerilog((ctx, lc) => lc .WriteTo.Console() .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) ); NLog Example: 1. Install NLog.Extensions.Logging package 2. Add NLog.config file 3. Configure in Program.cs: builder.Logging.ClearProviders(); builder.Logging.SetMinimumLevel(LogLevel.Information); builder.Host.UseNLog(); ✅ Both support structured logging, sinks, filtering, and rolling files.

How to Use Serilog or NLog? Serilog Example (Program.cs): builder.Host.UseSerilog((ctx, lc) =&gt; lc .WriteTo.Console() .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) ); NLog Example: Install NLog.E…

Mid PDF
What Frameworks Are Commonly Used? Answer: ● 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.

What Frameworks Are Commonly Used? Answer: xUnit – Popular, lightweight, supports parallel testing. NUnit – Rich assertion library. MSTest – Microsoft-supported, integrated in Visual Studio. Most modern ASP.NET Core proj…

Mid PDF
Profile queries with ToQueryString(). Example: var data = _context.Products.AsNoTracking().Select(p => new { p.Name, p.Price }).ToList(); ⚡ 18. How to use compiled queries?

Compiled queries improve performance by caching query translation. Example: private static readonly Func&lt;AppDbContext, decimal, IEnumerable&lt;Product&gt;&gt; _getExpensiveProducts = EF.CompileQuery((AppDbContext ctx,…

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

pp.MapHealthChecks("/health");

What interviewers expect

  • A clear definition tied to MVC in ASP.NET Core MVC projects
  • Trade-offs (performance, maintainability, security, cost)
  • When you would and would not use it in production

Real-world example

In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.

How to explain in the interview

  1. Define the concept in one or two sentences.
  2. Context — where it fits in ASP.NET Core MVC architecture.
  3. Example — a specific project, bug, or performance win.
  4. Trade-off — what you gain vs what you sacrifice.

Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.

Permalink & share

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

Role-based authorization restricts access based on user roles.

ssign a role:

wait _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 =>

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

});

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

uthorizationHandler<MinimumAgeRequirement>

{

protected override Task HandleRequirementAsync(

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

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

wait HttpContext.SignInAsync(

CookieAuthenticationDefaults.AuthenticationScheme,

new ClaimsPrincipal(identity));

🌐 10. How to integrate OAuth2 / OpenID Connect in

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

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

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

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

Apply [Authorize] at different levels:

Controller-level:

[Authorize]

public class OrdersController : Controller { ... }

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

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

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

pp.UseExceptionHandler("/Home/Error");

or

public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
context.Result = new ViewResult { ViewName = "Error" };
}
}

🧩 19. How to return partial views?

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:

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

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

builder.Services.AddHealthChecks(); app.MapHealthChecks("/health");

What interviewers expect

  • A clear definition tied to MVC in ASP.NET Core MVC projects
  • Trade-offs (performance, maintainability, security, cost)
  • When you would and would not use it in production

Real-world example

In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.

How to explain in the interview

  1. Define the concept in one or two sentences.
  2. Context — where it fits in ASP.NET Core MVC architecture.
  3. Example — a specific project, bug, or performance win.
  4. Trade-off — what you gain vs what you sacrifice.

Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.

Permalink & share

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
  • Custom events and telemetry

9⃣ How to Monitor Performance and Uptime?

Techniques:

Permalink & share

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

wait sqlContainer.StartAsync();

var options = new DbContextOptionsBuilder<AppDbContext>()

.UseSqlServer(sqlContainer.GetConnectionString())

.Options;

// Use context in tests

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

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

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

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

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

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!");
Permalink & share

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

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

You can use:

What interviewers expect

  • A clear definition tied to MVC in ASP.NET Core MVC projects
  • Trade-offs (performance, maintainability, security, cost)
  • When you would and would not use it in production

Real-world example

In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.

How to explain in the interview

  1. Define the concept in one or two sentences.
  2. Context — where it fits in ASP.NET Core MVC architecture.
  3. Example — a specific project, bug, or performance win.
  4. Trade-off — what you gain vs what you sacrifice.

Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.

Permalink & share

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

zure App Service PaaS Easy scaling, HTTPS

CI/CD GitHub Actions / Azure DevOps Automated build/test/deploy

Logging ILogger, Serilog, NLog Use structured logging

Monitoring Application Insights, Prometheus Track metrics, uptime

Health Checks ASP.NET Core HealthChecks Expose /health endpoints

This gives a complete production-ready workflow from deployment to monitoring.

dvanced & Modern Topics

Middleware Pipeline in Depth

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:

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

{

Console.WriteLine("Before Middleware 1");

wait next();

Console.WriteLine("After Middleware 1");

});

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

{

Console.WriteLine("Middleware 2");

wait next();

});

pp.Run(async context =>

{

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

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

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

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

});

wait connection.start();

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

5⃣ Background Services (IHostedService)

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

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

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

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

}));

});

pp.UseRateLimiter();

✅ Helps protect APIs from abuse or DoS attacks.

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

pp.UseExceptionHandler(errorApp =>

{

errorApp.Run(async context =>

{
var error =

context.Features.Get<IExceptionHandlerPathFeature>();

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

context.Response.StatusCode = 500;

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

});

});

1⃣1⃣ Anti-Forgery Tokens

  • Protects against CSRF attacks
  • In Razor:

<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

uth

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
  • 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" };

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

Integrating GraphQL

builder.Services.AddGraphQLServer()

.AddQueryType<Query>();

pp.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
Permalink & share

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?

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

Steps:

Permalink & share

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

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

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

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

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

Permalink & share

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

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

Answer: Hangfire or Quartz.NET for Background Jobs Hangfire Example: app.UseHangfireDashboard(); RecurringJob.AddOrUpdate(() =&gt; Console.WriteLine("Recurring job"), Cron.Daily); Quartz.NET: Supports cron-like scheduling and clustered execution.

What interviewers expect

  • A clear definition tied to MVC in ASP.NET Core MVC projects
  • Trade-offs (performance, maintainability, security, cost)
  • When you would and would not use it in production

Real-world example

In a production ASP.NET Core MVC application, teams apply this when handling user-facing features or integration boundaries. For example, you might use it during a sprint where reliability and observability matter—logging metrics, validating edge cases, and documenting the decision in an ADR so future developers understand why the approach was chosen.

How to explain in the interview

  1. Define the concept in one or two sentences.
  2. Context — where it fits in ASP.NET Core MVC architecture.
  3. Example — a specific project, bug, or performance win.
  4. Trade-off — what you gain vs what you sacrifice.

Tip: Practice aloud on Toolliyo mock interview or the Interview Q&A section before your real interview.

Permalink & share

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

How to Test Minimal APIs?

Answer:

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

Assert.NotEmpty(products);

Permalink & share

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

Health Checking in ASP.NET Core

builder.Services.AddHealthChecks()

.AddSqlServer(connectionString)

.AddCheck<CustomHealthCheck>("CustomCheck");

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

}
Permalink & share

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

How to Use Serilog or NLog?

Serilog Example (Program.cs):

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

.WriteTo.Console()

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

RollingInterval.Day)

);

NLog Example:

  • Install NLog.Extensions.Logging package
  • Add NLog.config file
  • Configure in Program.cs:

builder.Logging.ClearProviders();

builder.Logging.SetMinimumLevel(LogLevel.Information);

builder.Host.UseNLog();

✅ Both support structured logging, sinks, filtering, and rolling files.

Permalink & share

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

What Frameworks Are Commonly Used?

Answer:

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

Permalink & share

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:

modelBuilder.Entity<Product>()

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

ll 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.
  • For high-traffic apps, tune pool

settings in the connection string:

Max Pool Size=200; Min
Pool Size=5;

uthentication & Authorization

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