ASP.NET Core Practice Test

โ–ถ

ASP.NET Core application development has become one of the most sought-after skill sets in modern web engineering. Built by Microsoft as a complete rewrite of the classic ASP.NET framework, ASP.NET Core is open-source, cross-platform, and designed to run on Windows, macOS, and Linux alike. Whether you are building a small REST API or a large enterprise web portal, understanding asp net core application development fundamentals gives you a significant advantage in today's competitive job market.

ASP.NET Core application development has become one of the most sought-after skill sets in modern web engineering. Built by Microsoft as a complete rewrite of the classic ASP.NET framework, ASP.NET Core is open-source, cross-platform, and designed to run on Windows, macOS, and Linux alike. Whether you are building a small REST API or a large enterprise web portal, understanding asp net core application development fundamentals gives you a significant advantage in today's competitive job market.

At its core, ASP.NET Core uses a modular middleware pipeline that processes HTTP requests and responses. Unlike the legacy Web Forms or classic MVC approach, the new framework favors composition over configuration. Every feature โ€” routing, authentication, logging, dependency injection โ€” is added as a discrete middleware component that you opt into deliberately. This design keeps applications lean and makes performance tuning straightforward because you only pay for what you actually use in production.

One of the biggest shifts developers encounter when moving to ASP.NET Core is the unified programming model. You no longer maintain separate projects for MVC web apps and Web API services. A single ASP.NET Core project can serve HTML pages via Razor Views, return JSON from controller actions, stream files, and handle WebSocket connections simultaneously. This consolidation dramatically reduces the surface area of your solution structure and makes maintenance far easier over the long lifecycle of a product.

Dependency injection is baked into the framework rather than bolted on as a third-party library. The built-in IoC container supports three lifetime scopes โ€” transient, scoped, and singleton โ€” and integrates seamlessly with popular alternatives like Autofac or Lamar if you need more advanced features. Learning how to register services correctly from the start prevents a wide class of subtle bugs related to resource leaks, thread-safety issues, and inconsistent state across HTTP requests.

The configuration system in ASP.NET Core is equally powerful. Instead of a single Web.config file, configuration is layered from multiple sources: JSON files, environment variables, command-line arguments, Azure Key Vault, and custom providers. Values from later sources override those from earlier ones, enabling a clean pattern where developer defaults live in appsettings.json and production secrets are injected at runtime through environment variables without touching source code.

Testing is a first-class concern in ASP.NET Core application development. The framework ships with a TestServer and WebApplicationFactory class that lets you spin up a fully functional in-memory version of your application in milliseconds. You can write integration tests that exercise the complete HTTP stack โ€” middleware, routing, model binding, controllers, and database access โ€” without opening a browser or deploying to a server. This capability shortens feedback loops considerably and makes continuous integration pipelines reliable.

Performance benchmarks consistently place ASP.NET Core among the fastest web frameworks available across any programming language. The Techempower benchmarks show ASP.NET Core handling hundreds of thousands of plain-text responses per second on commodity hardware, and the Minimal API feature introduced in .NET 6 reduces overhead even further by eliminating controller base classes and reflection-heavy attribute routing. Understanding these performance characteristics helps you make informed architectural decisions as your application scales.

ASP.NET Core Application Development by the Numbers

๐Ÿ’ป
Top 3
Fastest Web Frameworks
๐ŸŒ
3 Platforms
Cross-Platform Support
๐Ÿ’ฐ
$112K
Avg. .NET Developer Salary
๐Ÿ“ˆ
34%
Market Share
๐Ÿ†
300K+
Minimal API throughput
Try Free ASP.NET Core Application Development Practice Questions

How to Set Up Your First ASP.NET Core Application

๐Ÿ“ฅ

Download the latest .NET 8 SDK from dotnet.microsoft.com. Run `dotnet --version` in your terminal to confirm the installation. The SDK includes the runtime, CLI tools, and project templates you need to start building immediately.

๐Ÿ—๏ธ

Use `dotnet new webapi -n MyApp` or `dotnet new mvc -n MyApp` to generate a starter project. The CLI creates the folder structure, Program.cs entry point, appsettings.json, and a sample controller so you can run the app within seconds.

โš™๏ธ

Open Program.cs and register your services in the dependency injection container using builder.Services. Then build the middleware pipeline with app.Use* calls in the correct order: exception handling, HTTPS redirection, static files, routing, authentication, and endpoints.

๐Ÿ’ก

Create controller classes or Minimal API endpoint handlers that call service layer classes. Keep controllers thin โ€” they should only coordinate input validation and return appropriate HTTP responses. Place all business rules and data access in separate service and repository classes.

๐Ÿงช

Add an xUnit or NUnit test project. Use WebApplicationFactory to write integration tests that hit your endpoints through the full middleware stack. Run `dotnet test` to execute all tests and `dotnet run` to start the development server and verify the app in your browser.

๐Ÿš€

Run `dotnet publish -c Release` to produce optimized output binaries. Deploy to Azure App Service, a Docker container, IIS on Windows, or Nginx on Linux. Configure environment variables for production secrets and verify health check endpoints after deployment.

Understanding the middleware pipeline is the single most important conceptual leap in ASP.NET Core application development. Middleware components are software pieces assembled in a chain where each component can inspect, modify, short-circuit, or pass along every HTTP request and response. The order in which you register middleware in Program.cs is the exact order that requests travel through them โ€” getting this sequence wrong causes subtle bugs that are hard to trace in production environments.

The routing system in ASP.NET Core handles the mapping between incoming URLs and the code that should execute for those URLs. Attribute routing using `[Route]`, `[HttpGet]`, `[HttpPost]` decorators on controller actions is the most common approach. Conventional routing using route templates defined centrally also works well for larger applications with consistent URL patterns. In .NET 6 and later, Minimal APIs let you define routes inline using lambda expressions โ€” `app.MapGet("/products/{id}", handler)` โ€” which is especially clean for microservices with small surface areas.

Model binding is another pillar of the request processing pipeline. When a request arrives, ASP.NET Core automatically extracts values from the route, query string, form body, or JSON payload and maps them to the parameters of your action method or endpoint handler. The `[FromBody]`, `[FromQuery]`, `[FromRoute]`, and `[FromHeader]` attributes let you be explicit about the source of each bound value, which is essential when building APIs that need to accept data from multiple sources in a single request.

Validation is tightly coupled with model binding through Data Annotations and the IValidatableObject interface. Decorating your model classes with attributes like `[Required]`, `[StringLength]`, `[Range]`, and `[EmailAddress]` causes ASP.NET Core to automatically check those constraints during model binding and populate ModelState.IsValid accordingly. For more complex business validation rules, the FluentValidation library integrates cleanly with the dependency injection system and keeps validation logic out of your controller actions.

Entity Framework Core is the officially recommended ORM for database access in ASP.NET Core applications. You define your data model as C# classes, configure relationships and column mappings using the Fluent API in OnModelCreating, and use DbContext as the unit of work. EF Core supports SQL Server, PostgreSQL, SQLite, MySQL, and Cosmos DB through interchangeable provider packages. Code-first migrations let you evolve your database schema in version-controlled C# files rather than manual SQL scripts, which is crucial for team environments.

Background processing is handled elegantly through the IHostedService and BackgroundService abstractions. Registering a class that inherits BackgroundService and overriding ExecuteAsync gives you a long-running background task that starts and stops with the web host lifecycle. For more sophisticated job scheduling โ€” recurring tasks, retry policies, delayed execution โ€” libraries like Hangfire or Quartz.NET integrate through the standard IHostedService interface and provide admin dashboards for monitoring job state.

Caching is a critical performance tool in any ASP.NET Core application. The framework provides IMemoryCache for in-process caching and IDistributedCache for distributed scenarios using Redis or SQL Server. Response caching middleware can cache entire HTTP responses at the network level, dramatically reducing database load for read-heavy endpoints. Output caching introduced in .NET 7 adds even more control with policy-based cache invalidation and vary-by rules. Choosing the right caching layer for each use case can reduce response times by an order of magnitude under real-world traffic patterns.

ASP.NET Core Authentication & Authorization
Test your knowledge of JWT, cookies, policies, and role-based access control.
ASP.NET Core Authentication & Authorization 2
Advanced questions on claims, middleware, OAuth2, and authorization handlers.

ASP.NET Core Development Patterns You Must Know

๐Ÿ“‹ MVC Pattern

The Model-View-Controller pattern separates an application into three distinct layers: Models represent data and business logic, Views render HTML output using Razor syntax, and Controllers act as coordinators that receive HTTP requests, call services, and select which view to render. This separation makes large ASP.NET Core web applications much easier to maintain because UI changes rarely require touching business logic and vice versa.

Controllers in ASP.NET Core inherit from the ControllerBase class for API use or the Controller class when they also need to return Razor Views. Action methods return IActionResult objects โ€” Ok(), NotFound(), BadRequest(), View(), RedirectToAction() โ€” that determine the HTTP status code and response body. Keeping action methods to 10 lines or fewer and delegating complex work to injected service classes is the clearest sign of a well-structured ASP.NET Core MVC application.

๐Ÿ“‹ Repository Pattern

The Repository pattern abstracts data access behind an interface, decoupling your business logic from any specific database technology. Define an IProductRepository interface with methods like GetByIdAsync, ListAllAsync, and AddAsync. The concrete implementation uses Entity Framework Core or Dapper to execute SQL, while your service classes depend only on the interface. This design makes unit testing trivial because you can substitute a mock repository that returns predefined data without touching a real database.

A common refinement is the Unit of Work pattern layered on top of repositories. A single IUnitOfWork interface exposes multiple repository properties and a SaveChangesAsync method. This ensures that multiple repository operations either all succeed or all fail together within a single database transaction. EF Core's DbContext already implements this pattern internally, so wrapping it in a Unit of Work class is most valuable when you need explicit transaction semantics across multiple aggregates.

๐Ÿ“‹ Minimal APIs

Minimal APIs were introduced in .NET 6 as a lightweight alternative to the full MVC controller stack. Instead of creating controller classes, you register HTTP endpoints directly in Program.cs using app.MapGet, app.MapPost, app.MapPut, and app.MapDelete calls that accept route patterns and handler delegates. This approach has measurably lower startup overhead and fewer abstraction layers, making it ideal for microservices or Azure Functions-style workloads where cold start time matters.

Minimal APIs support all the same features as MVC endpoints: model binding, validation, dependency injection into handler parameters, filters, route groups, and OpenAPI generation via Swashbuckle or the new Microsoft.AspNetCore.OpenApi package. Route groups introduced in .NET 7 let you apply common prefixes, middleware, and metadata to sets of related endpoints without repeating yourself. For teams building greenfield services on .NET 8, Minimal APIs are now the recommended starting point because they produce cleaner, more readable code with less ceremony than traditional controllers.

ASP.NET Core for Application Development: Strengths and Limitations

Pros

  • Cross-platform: runs natively on Windows, macOS, and Linux without code changes
  • Exceptional performance: consistently top-ranked in TechEmpower framework benchmarks
  • First-class dependency injection built into the framework core, no third-party setup needed
  • Unified model for MVC web apps, REST APIs, gRPC services, and real-time SignalR hubs
  • Rich tooling support in Visual Studio, VS Code, and JetBrains Rider with hot reload
  • Strong ecosystem: Entity Framework Core, Blazor, MAUI, Azure integration, and NuGet packages

Cons

  • Steeper learning curve than PHP or Node.js for developers new to typed, compiled languages
  • C# and .NET ecosystem knowledge required โ€” not a pick-up-and-go framework for complete beginners
  • Windows-centric tooling (Visual Studio) still dominates documentation despite cross-platform runtime
  • Entity Framework Core migrations can be brittle in large team environments without disciplined workflow
  • Razor Views feel verbose compared to modern JavaScript frameworks for highly interactive UIs
  • Breaking changes between major .NET versions (5, 6, 7, 8) require periodic migration effort
ASP.NET Core Authentication & Authorization 3
Challenge yourself with advanced auth scenarios, token validation, and identity configuration.
ASP.NET Core Configuration & Environments
Test your mastery of appsettings, environment variables, secrets, and IOptions patterns.

ASP.NET Core Application Development Best Practices Checklist

Register all services in Program.cs using the correct lifetime: transient, scoped, or singleton
Always validate incoming request models using Data Annotations or FluentValidation before processing
Use ILogger<T> for structured logging rather than Console.WriteLine or Trace statements
Store secrets in environment variables or Azure Key Vault โ€” never commit them to source control
Apply the Repository pattern to abstract database access and simplify unit testing
Configure CORS policies explicitly and restrict allowed origins in production environments
Enable HTTPS redirection middleware and use HSTS headers on all production deployments
Write integration tests with WebApplicationFactory to cover the full request/response pipeline
Use async/await consistently on all I/O operations to avoid blocking thread pool threads
Implement health check endpoints at /health and /ready for container orchestration platforms
Middleware Order Is Not Optional โ€” It Is Architecture

The single most common source of subtle bugs in ASP.NET Core applications is incorrect middleware ordering. Exception handling middleware must be registered first so it can catch errors from everything downstream. Authentication must run before authorization. Routing must be called before endpoint execution. Always follow the Microsoft-recommended order: UseExceptionHandler, UseHsts, UseHttpsRedirection, UseStaticFiles, UseRouting, UseAuthentication, UseAuthorization, UseEndpoints.

Deploying ASP.NET Core applications has never been more flexible. You can target a self-contained deployment where the .NET runtime is bundled with your application binary, meaning the host machine needs no pre-installed .NET SDK at all. This approach is ideal for Docker containers and serverless environments where you control the exact image layers. Alternatively, a framework-dependent deployment produces a smaller output but requires the matching .NET runtime to be installed on the target machine, which is common for shared hosting or corporate IIS servers.

Docker and container-based deployments have become the dominant pattern for production ASP.NET Core workloads. Microsoft publishes official base images on Docker Hub โ€” `mcr.microsoft.com/dotnet/aspnet:8.0` for the runtime and `mcr.microsoft.com/dotnet/sdk:8.0` for building. A multi-stage Dockerfile first uses the SDK image to compile and publish the application, then copies only the published output into the smaller runtime image. This pattern keeps production images lean โ€” often under 200 MB โ€” and avoids shipping SDK tools to production servers.

Azure App Service is the simplest managed hosting option for teams already in the Microsoft cloud ecosystem. You can deploy directly from Visual Studio publish profiles, GitHub Actions, Azure DevOps pipelines, or Zip Deploy via the Azure CLI. App Service handles TLS certificate management, auto-scaling, deployment slots for blue-green releases, and integration with Application Insights for monitoring. For teams without dedicated DevOps engineers, App Service provides a production-ready platform with minimal operational overhead.

Kubernetes has become the standard for large-scale ASP.NET Core deployments. Containerized applications run in pods managed by deployments, and Kubernetes handles scheduling, health checking, rolling updates, and automatic restarts. The ASP.NET Core health check endpoints โ€” built using the `AddHealthChecks()` extension method โ€” map directly to Kubernetes liveness and readiness probes. When the readiness probe returns unhealthy, Kubernetes stops routing traffic to that pod while it recovers, enabling zero-downtime deployments even for stateful applications.

Nginx and Apache are popular reverse proxies for hosting ASP.NET Core on Linux servers managed outside the cloud. You run the ASP.NET Core process using the built-in Kestrel web server and configure Nginx to proxy requests from ports 80 and 443 to the Kestrel port (typically 5000). The ASP.NET Core team publishes detailed documentation for this setup, including the ForwardedHeaders middleware configuration required so that your application correctly reads the client IP address and original scheme headers that Nginx forwards through its proxy layer.

Continuous integration and continuous deployment pipelines are essential for professional ASP.NET Core projects. GitHub Actions, Azure DevOps, and GitLab CI all have first-class .NET support. A typical pipeline restores NuGet packages, compiles the solution, runs unit and integration tests, publishes a Docker image, and deploys to staging automatically on every pull request merge. Adding code coverage requirements and static analysis using tools like SonarCloud prevents quality regressions as the team grows and the codebase matures.

Monitoring and observability round out a production-ready ASP.NET Core deployment. Application Insights, Prometheus with Grafana, and the OpenTelemetry SDK all integrate with ASP.NET Core through the standard ILogger and DiagnosticSource APIs. The `AddOpenTelemetry()` extension method in .NET 8 makes it straightforward to emit traces, metrics, and logs to any OpenTelemetry-compatible backend. Setting up distributed tracing from day one means that when a performance regression appears in production, you can trace a single slow request through every service and database call that contributed to its response time.

Preparing for ASP.NET Core certification exams and job interviews requires a thorough understanding of topics that span the full stack of the framework. Microsoft's AZ-204 (Developing Solutions for Microsoft Azure) exam covers ASP.NET Core deployment heavily, while the broader .NET ecosystem knowledge assessed in developer interviews touches middleware pipelines, Entity Framework Core, authentication flows, and performance tuning. Building real projects is irreplaceable, but structured practice with targeted questions accelerates your readiness significantly.

Authentication and authorization are among the highest-weight topics in any ASP.NET Core assessment. You need to understand the difference between authentication schemes (cookies, JWT bearer, API keys) and how the IAuthenticationService resolves them at runtime. Authorization in ASP.NET Core is policy-based: you define named policies that combine claims requirements, custom authorization handlers, and role checks, then apply them to controllers or endpoints via the `[Authorize(Policy = "RequireAdmin")]` attribute. Mixing these concepts incorrectly is one of the most common exam and interview mistakes.

Configuration and environment management is another heavy topic area. Questions frequently explore how the IConfiguration hierarchy resolves values from multiple sources, how to use the Options pattern (IOptions<T>, IOptionsSnapshot<T>, IOptionsMonitor<T>) to bind configuration sections to strongly-typed C# classes, and how to provide different values for Development, Staging, and Production environments. Understanding which IOptions variant is appropriate for hot-reload scenarios versus singleton services catches many candidates off guard.

Dependency injection subtleties trip up even experienced developers. Common exam scenarios include: injecting a scoped service into a singleton (creates a captive dependency bug), resolving services inside middleware constructors versus in the Invoke method, using IServiceScopeFactory to create manual scopes in background services, and registering open generic types. Each of these patterns has specific implications for application correctness and testability that examiners love to probe with edge-case questions.

Performance optimization questions appear in both certification exams and senior developer interviews. Topics include response compression middleware, output caching versus response caching versus in-memory caching, minimizing allocations with Span<T> and ArrayPool in high-throughput scenarios, connection pooling for HttpClient via IHttpClientFactory, and using ValueTask instead of Task for hot paths. You do not need to memorize benchmark numbers, but understanding the architectural reasons why each optimization works is essential.

SignalR and real-time communication topics are increasingly common as more applications require live updates โ€” dashboards, notifications, collaborative editing. ASP.NET Core SignalR uses WebSockets with long-polling fallback and provides a hub abstraction for grouping clients and broadcasting messages. Scaled-out deployments require a backplane โ€” typically Azure SignalR Service or Redis โ€” because multiple server instances cannot share in-memory connection state. Interview questions often explore how you would architect a chat system or live scoreboard using these primitives.

Hands-on practice is the most effective preparation strategy for any ASP.NET Core assessment. Build a small but complete application that includes authentication with JWT tokens, a database via EF Core with migrations, a background service, configuration from multiple sources, and an integration test suite. Then take targeted practice quizzes on specific feature areas โ€” authentication, configuration, middleware โ€” to identify and close knowledge gaps before your exam or interview. This combined approach of project-based learning and focused quiz practice consistently produces the best results among developers preparing for .NET certification and technical hiring screens.

Practice ASP.NET Core Configuration & Environment Questions Now

Practical tips from experienced ASP.NET Core developers consistently point to the same set of habits that separate good applications from fragile ones. Start by keeping your Program.cs clean and organized. Group service registrations into extension methods โ€” `builder.Services.AddApplicationServices()`, `builder.Services.AddInfrastructure()` โ€” so the entry point reads as a high-level summary of your application's composition rather than a long scroll of low-level calls. This organization pays dividends when onboarding new team members or debugging startup failures.

Learn to read the ASP.NET Core source code on GitHub. The framework is fully open-source and the source is well-organized. When a middleware behaves unexpectedly or a method does something surprising, reading the actual implementation takes five minutes and gives you certainty that no documentation summary can match. Developers who build this habit find themselves far more confident in their understanding of edge cases and far less reliant on trial-and-error debugging in production environments.

Use the ILogger<T> structured logging interface from the very first line of production code. Structured logs โ€” where message templates have named placeholders like `{OrderId}` rather than string-interpolated values โ€” are queryable in log aggregation tools like Elastic, Splunk, and Azure Monitor. When you log `_logger.LogInformation("Order {OrderId} created for user {UserId}", order.Id, userId)`, those values become searchable fields. This practice costs nothing during development and saves hours during production incident investigations.

Embrace nullable reference types, which are enabled by default in .NET 6+ projects. The compiler warnings that nullable annotations generate are not noise โ€” they are the framework telling you about places where a null dereference can crash your application at runtime. Treating these warnings as errors in your CI pipeline (`<TreatWarningsAsErrors>true</TreatWarningsAsErrors>`) catches an entire category of production bugs at compile time. Pair this with the `required` keyword on C# 11 properties to enforce object initialization discipline.

Write your API contracts with OpenAPI documentation from the start. The Swagger UI generated by Swashbuckle or the built-in Microsoft.AspNetCore.OpenApi package in .NET 9 gives your front-end team and API consumers a living, interactive reference without any separate documentation effort. XML doc comments on controllers (`///

`) flow directly into the Swagger spec. Adding `[ProducesResponseType]` attributes documents the possible HTTP status codes your endpoints return, which matters for both human consumers and code generators.

Profile your application before you optimize it. The ASP.NET Core diagnostics middleware, dotnet-trace, dotnet-counters, and Visual Studio's profiler tools give you data-driven insight into where time and allocations are actually going. Developers who optimize based on intuition frequently spend days tuning code that contributes less than one percent of real-world response time. Identify the actual hotspots first โ€” usually database queries and serialization โ€” then apply targeted optimizations like query projection, compiled EF Core queries, or System.Text.Json source generation.

Stay current with .NET release cadence. Microsoft ships a major .NET version every November. Even-numbered releases (6, 8, 10) are Long-Term Support versions that receive patches for three years. Odd-numbered releases (5, 7, 9) are Standard-Term Support with eighteen months of patches. Running your production applications on current LTS releases ensures you receive security patches and can target modern language features. The `dotnet-outdated` CLI tool scans your project files and reports which NuGet packages have newer versions available, making dependency hygiene a routine ten-minute task rather than a quarterly scramble.

ASP.NET Core Configuration & Environments 2
Intermediate configuration questions covering IOptions patterns, secrets, and environment switching.
ASP.NET Core Configuration & Environments 3
Advanced environment configuration, custom providers, and production secrets management.

Asp Net Core Questions and Answers

What is ASP.NET Core and how is it different from classic ASP.NET?

ASP.NET Core is a complete, open-source rewrite of the original ASP.NET framework. Unlike classic ASP.NET, which only ran on Windows with IIS, ASP.NET Core runs cross-platform on Windows, macOS, and Linux. It features a modular middleware pipeline, built-in dependency injection, dramatically better performance, and a unified model that handles both MVC web applications and REST API services within a single project.

Which .NET version should I use for a new ASP.NET Core project in 2024?

.NET 8 is the recommended choice for new projects started in 2024. It is a Long-Term Support release receiving patches until November 2026, which means three years of security fixes without requiring a major version migration. .NET 8 also delivers significant performance improvements over .NET 6 and includes mature Minimal API features, Native AOT compilation support, and improved source generation for JSON serialization.

What is middleware in ASP.NET Core and why does order matter?

Middleware in ASP.NET Core are software components assembled in a pipeline that process HTTP requests sequentially. Each component can inspect or modify the request, pass it to the next component, or short-circuit the pipeline and return a response directly. Order matters critically because components like authentication must run before authorization, and exception handling must be registered first so it can catch errors thrown by downstream components including your own business logic code.

How does dependency injection work in ASP.NET Core?

ASP.NET Core includes a built-in IoC container that resolves constructor dependencies automatically. You register services in Program.cs using builder.Services.AddSingleton, AddScoped, or AddTransient depending on how long each service instance should live. Singleton creates one instance for the entire application lifetime, scoped creates one per HTTP request, and transient creates a new instance every time the service is requested. The framework then injects the correct instance wherever the service type is declared as a constructor parameter.

What is the difference between IOptions, IOptionsSnapshot, and IOptionsMonitor?

All three interfaces provide access to strongly-typed configuration sections bound to C# classes, but they differ in lifetime and change detection. IOptions is a singleton that reads configuration once at startup and never updates. IOptionsSnapshot is scoped and reloads configuration on each HTTP request, useful when you need fresh values per request. IOptionsMonitor is a singleton that actively watches for configuration changes and raises an event when values change, ideal for background services that need live updates.

How do you secure an ASP.NET Core API with JWT tokens?

Add the Microsoft.AspNetCore.Authentication.JwtBearer NuGet package and call builder.Services.AddAuthentication().AddJwtBearer() in Program.cs, providing your token validation parameters including the issuer, audience, and signing key. Register UseAuthentication() and UseAuthorization() in the middleware pipeline in that order. Decorate your controllers or actions with the [Authorize] attribute to require a valid token. Generate tokens on login by creating a JwtSecurityToken with claims and signing it with your secret key.

What is Entity Framework Core and when should I use it?

Entity Framework Core is Microsoft's official object-relational mapper for .NET that lets you query and update a database using C# objects instead of raw SQL. It supports SQL Server, PostgreSQL, SQLite, MySQL, and Cosmos DB. Use EF Core when your data model is relatively normalized, you want code-first schema migrations, or you prioritize developer productivity. For high-throughput scenarios that require hand-tuned SQL, consider Dapper as a lighter alternative that maps query results to C# objects without the overhead of change tracking.

How do you write integration tests for an ASP.NET Core application?

Use the WebApplicationFactory<TProgram> class from the Microsoft.AspNetCore.Mvc.Testing NuGet package. Inherit from it in your test class and use the CreateClient() method to get an HttpClient that sends requests through your application's full middleware pipeline in memory without binding to a port. You can override ConfigureWebHost to substitute test doubles for external dependencies like databases or third-party APIs. This approach tests routing, model binding, validation, authentication, and business logic together in milliseconds.

What are Minimal APIs in ASP.NET Core and when should I use them?

Minimal APIs are a lightweight alternative to MVC controllers introduced in .NET 6. You define HTTP endpoints directly in Program.cs using app.MapGet, app.MapPost, and similar extension methods with handler lambdas or named functions. They have lower startup overhead, fewer abstraction layers, and less ceremony than controllers, making them excellent for microservices, Azure Functions replacements, or teams that want simpler code. For large applications with many endpoints, traditional controllers may still provide better organization through their class-based grouping.

How do you handle configuration secrets safely in ASP.NET Core?

During local development, use the .NET Secret Manager tool by running `dotnet user-secrets init` and `dotnet user-secrets set "Key" "Value"`. Secrets Manager stores values outside your project directory so they are never committed to source control. In production, use environment variables injected by your hosting platform, Azure Key Vault via the Microsoft.Extensions.Configuration.AzureKeyVault package, or AWS Secrets Manager. Always configure your CI/CD pipeline to inject secrets through environment variables rather than reading from appsettings files.
โ–ถ Start Quiz