Top 50 .NET Core Interview Questions & Answers
✅ Top 50 .NET Core Interview Questions & Answers
(with Definition + Details + Real Example + Syntax + Code)
1. What is .NET Core?
Definition: .NET Core is a free, open-source, cross-platform framework maintained by Microsoft. It allows developers to build web apps, APIs, microservices, cloud-native solutions, desktop, and mobile applications.
Details: It is modular, lightweight, high-performance, and can run on Windows, Linux, and macOS.
Real-Time Example: A bank runs its customer portal on Linux servers using .NET Core.
Syntax:
dotnet new webapi -n BankAPI
2. What are the advantages of .NET Core?
Definition: Benefits of using .NET Core compared to traditional .NET Framework.
Details:
-
Cross-platform
-
High performance with Kestrel server
-
Supports microservices and containers (Docker, Kubernetes)
-
Built-in Dependency Injection
-
Unified framework for Web, API, and MVC
Real-Time Example: An e-commerce site migrates from .NET Framework to .NET Core to deploy on Linux-based AWS servers.
3. What is Kestrel?
Definition: Kestrel is the default cross-platform web server in ASP.NET Core.
Details: It is lightweight and very fast, designed to handle high loads. Often runs behind a reverse proxy like IIS or Nginx.
Real-Time Example: An e-commerce site handles thousands of concurrent users using Kestrel + Nginx.
Code Example:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel();
webBuilder.UseStartup<Startup>();
});
4. What is Middleware?
Definition: Middleware are software components that handle requests/responses in the ASP.NET Core pipeline.
Details: Middleware executes in sequence and can modify requests before reaching the controller or modify responses before returning.
Real-Time Example: Authentication middleware validates JWT tokens before reaching APIs.
Code Example:
app.Use(async (context, next) =>
{
Console.WriteLine("Request started");
await next();
Console.WriteLine("Response completed");
});
5. Difference between .NET Core and .NET 5/6/7?
Definition:
-
.NET Core existed till version 3.1
-
From .NET 5, Microsoft merged everything into .NET Unified Platform
Details:
-
.NET 5+ includes support for desktop, mobile, cloud, and gaming in one platform.
-
Regular updates with Long Term Support (LTS).
Real-Time Example: Companies migrate apps from .NET Framework/Core to .NET 6 (LTS) for better support.
6. What is Dependency Injection (DI)?
Definition: DI is a design pattern where dependencies are provided instead of being created inside a class.
Details: ASP.NET Core has built-in DI with AddSingleton, AddScoped, and AddTransient.
Real-Time Example: Injecting a logging service into multiple controllers.
Code Example:
public interface IMessage { string GetMessage(); }
public class HelloMessage : IMessage { public string GetMessage() => "Hello"; }
services.AddScoped<IMessage, HelloMessage>();
public class HomeController : Controller
{
private readonly IMessage _msg;
public HomeController(IMessage msg) { _msg = msg; }
public IActionResult Index() => Content(_msg.GetMessage());
}
7. What are Controllers?
Definition: Controllers handle HTTP requests and return responses (JSON, HTML, etc.).
Details: Controllers usually inherit from ControllerBase or Controller.
Real-Time Example: A ProductController serves /api/products.
Code Example:
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(new[] { "Laptop", "Phone" });
}
8. What is Startup.cs?
Definition: Startup.cs configures services and middleware.
Details: Contains two methods:
-
ConfigureServices()→ register services -
Configure()→ setup request pipeline
Real-Time Example: Register EF Core, Authentication, and CORS policies here.
Code Example:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}
9. What is EF Core?
Definition: EF Core is an ORM (Object Relational Mapper) for database operations.
Details: Supports LINQ queries, migrations, multiple databases (SQL Server, MySQL, PostgreSQL).
Real-Time Example: A payroll app uses EF Core to fetch employee salary from SQL Server.
Code Example:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
10. What are Migrations in EF Core?
Definition: Migrations update database schema from model classes.
Details: dotnet ef command line is used for migrations.
Real-Time Example: Adding a new Salary column to Employee table.
Syntax:
dotnet ef migrations add AddSalaryColumn
dotnet ef database update
11. What is Singleton, Scoped, Transient in DI?
Definition:
-
Singleton → one instance for whole app
-
Scoped → one instance per request
-
Transient → new instance every time
Real-Time Example:
-
Singleton: Logger
-
Scoped: User session
-
Transient: Random number generator
Code Example:
services.AddSingleton<ILog, LogService>();
services.AddScoped<IUserService, UserService>();
services.AddTransient<IEmailService, EmailService>();
12. How does Logging work in .NET Core?
Definition: Logging helps track errors, info, and warnings.
Details: Built-in providers: Console, Debug, EventLog, Azure.
Real-Time Example: Log every failed payment attempt.
Code Example:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) => _logger = logger;
public IActionResult Index()
{
_logger.LogInformation("Page Loaded");
return View();
}
}
13. What are Filters?
Definition: Filters are used for cross-cutting concerns (logging, caching, auth).
Details: Types → Action, Exception, Authorization, Resource filters.
Real-Time Example: Apply a filter for logging all API requests.
Code Example:
public class LogActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context) =>
Console.WriteLine("Before action");
public void OnActionExecuted(ActionExecutedContext context) =>
Console.WriteLine("After action");
}
14. What is Routing?
Definition: Routing decides which controller/action handles a request.
Details: Two types:
-
Convention-based
-
Attribute-based
Real-Time Example: /products/10 → ProductController.Get(10)
Code Example:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
15. How do you handle Global Exceptions?
Definition: Global exception handling catches errors at application level.
Details: Use app.UseExceptionHandler() or custom middleware.
Real-Time Example: Show a friendly error page if DB connection fails.
Code Example:
app.UseExceptionHandler("/Home/Error");
16. What is gRPC?
Definition: gRPC is a high-performance Remote Procedure Call framework.
Details: Uses HTTP/2 and Protobuf (binary format).
Real-Time Example: Used in microservices communication in banking systems.
Code Example:
services.AddGrpc();
app.UseEndpoints(endpoints =>
{
endpoints.MapGrpcService<MyGrpcService>();
});
17. Difference between Web API in .NET Framework vs Core?
Definition:
-
.NET Framework Web API → Windows only, heavy, separate from MVC.
-
.NET Core API → Lightweight, cross-platform, unified with MVC.
Real-Time Example: APIs migrated to Core for Docker deployment.
Code Example:
dotnet new webapi
18. How to implement Caching?
Definition: Caching stores frequently used data in memory.
Details: Supports In-Memory, Distributed, and Response caching.
Real-Time Example: Cache product catalog to avoid frequent DB calls.
Code Example:
services.AddMemoryCache();
if (!_cache.TryGetValue("time", out string currentTime))
{
currentTime = DateTime.Now.ToString();
_cache.Set("time", currentTime, TimeSpan.FromMinutes(1));
}
19. What is JWT Authentication?
Definition: JWT (JSON Web Token) is a secure, token-based authentication method.
Details: Token contains user claims, signed using a secret key.
Real-Time Example: A mobile app uses JWT token for login and API calls.
Code Example:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("MySecretKey"))
};
});
20. What are Health Checks?
Definition: Health checks verify if the app, database, or services are working.
Details: Expose /health endpoint for monitoring tools.
Real-Time Example: Kubernetes checks health endpoint before routing traffic.
Code Example:
services.AddHealthChecks();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/health");
});
21. What are Tag Helpers in ASP.NET Core?
Definition: Tag helpers allow server-side code to participate in creating HTML.
Details: Strongly typed, IntelliSense-supported.
Real-Time Example: Use asp-for to bind a model property to input.
Code Example:
<input asp-for="Name" class="form-control" />
22. What is ViewComponent in ASP.NET Core?
Definition: ViewComponents are like partial views but with logic.
Details: Used for reusable UI sections.
Real-Time Example: Sidebar showing recent blog posts.
Code Example:
public class RecentPostsViewComponent : ViewComponent
{
public IViewComponentResult Invoke() => View("Default", new[] { "Post1", "Post2" });
}
23. What is SignalR?
Definition: SignalR is a library for real-time communication (WebSockets).
Details: Enables server → client push.
Real-Time Example: Chat apps, stock price updates.
Code Example:
services.AddSignalR();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chatHub");
});
24. What is Minimal API in .NET 6+?
Definition: Minimal APIs allow creating lightweight APIs without full controllers.
Details: Simple syntax using lambda expressions.
Real-Time Example: Microservices exposing quick APIs.
Code Example:
var app = WebApplication.CreateBuilder(args).Build();
app.MapGet("/hello", () => "Hello World");
app.Run();
25. What is Cross-Origin Resource Sharing (CORS)?
Definition: CORS allows APIs to be accessed from different domains.
Details: Important for SPAs (React, Angular).
Real-Time Example: React app calls ASP.NET Core API.
Code Example:
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
app.UseCors("AllowAll");
Comments
Post a Comment