ASP.NET Core
ASP.NET Core is an open-source, cross-platform, high-performance web framework developed by Microsoft for building modern, cloud-native web applications and services on the .NET platform.[1] It enables developers to create fast, secure, and scalable solutions that run on Windows, Linux, and macOS, supporting scenarios from simple APIs to complex enterprise applications.[1] Unlike its predecessor ASP.NET on the .NET Framework, ASP.NET Core is modular and lightweight, allowing for greater flexibility and reduced overhead in deployment.[1] The framework originated as a redesign of ASP.NET, with its initial release as .NET Core 1.0 on June 27, 2016, marking Microsoft's shift toward a unified, open-source ecosystem.[2] Subsequent versions followed an annual release cadence, with long-term support (LTS) editions providing extended stability, such as .NET Core 2.1 (2018) and .NET 6.0 (2021).[2] In November 2020, .NET Core was rebranded simply as .NET starting with version 5.0, unifying the platform under a single name while ASP.NET Core continued to evolve alongside it.[2] Key features of ASP.NET Core include a lightweight and modular HTTP request pipeline, the cross-platform Kestrel web server for handling requests, and built-in support for dependency injection to enhance testability and maintainability.[1] It integrates Razor for server-side templating to build dynamic views, Blazor for interactive client-side web UIs using C#, and Entity Framework Core for efficient data access across relational and non-relational databases.[1] Security is prioritized through features like built-in authentication, authorization, and HTTPS enforcement, while its design supports microservices, containerization with Docker, and deployment to cloud platforms like Azure.[1] As of November 2025, the current version is ASP.NET Core 10.0, released on November 11, 2025, which introduces enhancements in Blazor for improved web UI development, minimal APIs for streamlined backend services, OpenAPI support, and better performance optimizations.[2] This version aligns with .NET 10, a long-term support (LTS) release with support until November 2028, enabling developers to build robust applications that meet modern demands for speed, scalability, and cross-platform compatibility.[2]Overview
Definition and Purpose
ASP.NET Core is a free, open-source, cross-platform framework for developing modern, cloud-native web applications, web APIs, and microservices using the .NET platform. It enables developers to build high-performance applications that run on Windows, Linux, and macOS, supporting a wide range of deployment scenarios from on-premises servers to cloud environments.[3] The primary purposes of ASP.NET Core include facilitating high-performance server-side rendering for dynamic web pages, creating RESTful web services for API-driven architectures, enabling real-time web functionality through libraries like SignalR, and supporting scalable deployments in cloud-native settings. These capabilities make it suitable for constructing interactive user interfaces, backend services, and distributed systems that require low latency and high throughput.[4] A key concept in ASP.NET Core is its modular design, which allows developers to select only the necessary NuGet packages for their application, thereby reducing the overall size of the deployment and improving startup times.[4] This approach contrasts with more monolithic structures by promoting lightweight, composable components that enhance portability and efficiency across different hosting environments.[5] The framework represents a significant shift from the original ASP.NET, which was tightly coupled to the Windows-only .NET Framework, toward a redesigned, modular architecture optimized for cross-platform portability and modern development practices.[6] This evolution addresses the need for broader compatibility and reduced overhead in contemporary software ecosystems.[7]Relation to ASP.NET and .NET Ecosystem
ASP.NET Core represents a complete redesign and rewrite of the original ASP.NET framework, diverging significantly from its predecessor by prioritizing cross-platform compatibility across Windows, Linux, and macOS, whereas classic ASP.NET was inherently tied to the Windows-only .NET Framework.[8][9] This shift eliminates backward compatibility with ASP.NET Framework applications, requiring developers to adopt new patterns and APIs for web development, though it enables higher performance and reduced infrastructure costs through efficient resource utilization.[8] Built atop the modern .NET runtime—initially .NET Core from version 1.0 and unified under .NET 5 and subsequent releases—ASP.NET Core integrates seamlessly with the broader .NET ecosystem, sharing foundational libraries such as Entity Framework Core for data access and ORM capabilities.[10] This unification streamlines development by providing a single platform for building server-side applications, leveraging C#, F#, and other .NET languages without the fragmentation of legacy .NET Framework dependencies.[10] Developers benefit from unified tooling, including support in Visual Studio for comprehensive project management and VS Code for lightweight, cross-platform editing. Migrating from classic ASP.NET to ASP.NET Core involves targeted tools like the .NET Upgrade Assistant, which analyzes codebases, identifies incompatibilities, and automates project conversions to newer .NET versions, facilitating a structured porting process.[11] This tool supports incremental upgrades, allowing teams to modernize applications while minimizing disruptions, and highlights benefits such as enhanced scalability and cloud-native readiness.[11] Within the .NET family, ASP.NET Core interconnects with technologies like Blazor for interactive client-side web UIs using C#, .NET MAUI for cross-platform desktop and mobile applications via Blazor Hybrid, and Azure services for seamless cloud deployment and hosting.[12] These ties foster an interconnected ecosystem where ASP.NET Core serves as the web backbone, enabling full-stack .NET solutions from backend APIs to frontend experiences and beyond.[12][13]History
Origins and Development
ASP.NET Core originated as a key component of the broader .NET Core initiative, announced by Microsoft on December 4, 2014, to overcome the limitations of the traditional ASP.NET Framework, which was tightly coupled to Windows and suffered from monolithic bloat that hindered scalability and deployment flexibility.[14] This redesign was spearheaded by Microsoft engineers, with collaborative input from the .NET Foundation, an independent organization established to steward open-source .NET projects and foster community-driven enhancements.[15] The effort addressed the Framework's platform dependencies by creating a lean, modular runtime capable of running on Windows, Linux, and macOS, thereby broadening accessibility for developers beyond the Windows ecosystem.[8] The development process involved a ground-up modular redesign, emphasizing composability through NuGet packages to allow developers to include only necessary components, reducing overhead and improving maintainability. The first preview of what was then called ASP.NET 5 (later rebranded as ASP.NET Core) emerged in 2015, marking an early opportunity for testing core functionalities like the Kestrel web server. Central to this process was the commitment to open-source development under the MIT license, with the codebase hosted on GitHub to enable transparent community feedback, issue tracking, and contributions from external developers.[16] This approach not only accelerated iteration but also aligned with Microsoft's evolving strategy toward collaborative software ecosystems, integrating thousands of pull requests during the pre-release phase.[17] Key motivations for ASP.NET Core's creation included enabling cloud-native application development, seamless integration with containerization technologies like Docker, and support for microservices architectures, which demanded lightweight, portable runtimes for distributed systems. These goals positioned ASP.NET Core as a competitive alternative to frameworks like Node.js, known for its event-driven model in real-time apps, and [Spring Boot](/page/Spring Boot), valued for its Java-based enterprise microservices.[14] By prioritizing cross-platform compatibility and reduced deployment footprints, the project aimed to meet the rising demands of cloud environments such as Azure, where traditional ASP.NET's Windows-centric design posed barriers.[8] Early milestones highlighted a strong emphasis on performance optimization, with the development team targeting top rankings in independent benchmarks like TechEmpower's Web Framework Benchmarks to validate throughput and latency improvements over predecessors. Additionally, the integration of the Roslyn compiler platform enabled faster compilation times and richer code analysis during builds, streamlining the iterative development cycle for web applications.[18][19]Release Timeline
ASP.NET Core has followed a structured release cadence since its inception, aligning closely with the .NET runtime's versioning and support model, with major versions released annually starting from 2016.[20] Early releases focused on establishing cross-platform foundations, while later versions unified under the .NET branding from version 5.0 onward.[2] The framework receives monthly servicing updates for security and reliability fixes during its support period.[20] The following table summarizes key ASP.NET Core versions, their release dates, and end-of-support dates, as ASP.NET Core shares the same lifecycle as .NET and .NET Core.[2]| Version | Release Date | End of Support Date | Support Type |
|---|---|---|---|
| 1.0 | June 27, 2016 | June 27, 2019 | STS |
| 1.1 | November 16, 2016 | June 27, 2019 | STS |
| 2.0 | August 14, 2017 | October 1, 2018 | STS |
| 2.1 | May 30, 2018 | August 21, 2021 | LTS |
| 2.2 | December 4, 2018 | December 23, 2019 | STS |
| 3.0 | September 23, 2019 | March 3, 2020 | STS |
| 3.1 | December 3, 2019 | December 13, 2022 | LTS |
| 5.0 | November 10, 2020 | May 10, 2022 | STS |
| 6.0 | November 8, 2021 | November 12, 2024 | LTS |
| 7.0 | November 8, 2022 | May 14, 2024 | STS |
| 8.0 | November 14, 2023 | November 10, 2026 | LTS |
| 9.0 | November 12, 2024 | November 10, 2026 | STS |
| 10.0 | November 11, 2025 | November 14, 2028 | LTS |
Architecture
Hosting Model
ASP.NET Core applications are hosted using the .NET Generic Host, which manages the application's lifetime, dependency injection, logging, configuration, and hosted services, including the web server for HTTP workloads.[23] The IHost interface serves as the core abstraction for building and running the host, encapsulating all necessary resources and starting registered IHostedService implementations upon initialization.[24] From .NET 6 onward, the hosting model has been unified and simplified in a singleProgram.cs file, where the WebApplicationBuilder creates and configures the host, replacing the previous Startup class pattern.[25] This minimal hosting approach streamlines app startup for both web and non-web scenarios, with web applications typically invoking ConfigureWebHostDefaults to set up the Kestrel server by default.[23]
Kestrel is the default cross-platform web server included in ASP.NET Core project templates, designed for high performance and compatibility across Windows, Linux, and macOS.[26] It supports HTTP/1.1, HTTP/2 (with HTTP/2 disabled on macOS in current releases), HTTPS, WebSockets, Unix sockets, and HTTP/3 (on supported platforms).[27][26] For production environments exposed to the internet, Kestrel is typically configured behind a reverse proxy such as IIS on Windows or Nginx on Linux to handle features like load balancing, SSL termination, and static file serving.[28] Endpoints and options for Kestrel can be customized via code, appsettings.json, or environment variables, allowing fine-tuned control over listening ports, limits, and security settings.[29]
On Windows, ASP.NET Core supports hosting within Internet Information Services (IIS), which provides a managed environment for deployment and process management via the ASP.NET Core Module (ANCM).[30] In out-of-process mode—the default for new applications—the app runs in a separate process from the IIS worker process (w3wp.exe), with ANCM proxying requests to Kestrel on a dynamic port, offering isolation but introducing minor latency from inter-process communication.[31] In-process hosting, enabled by setting AspNetCoreHostingModel to InProcess in web.config, runs the app directly within the IIS process using the IIS HTTP Server module, yielding higher throughput and reduced overhead at the cost of shared process space.[32] For development, IIS Express runs applications out-of-process with Kestrel, facilitating local testing without full IIS installation.[30] Performance tuning often involves selecting modes based on throughput needs, with in-process preferred for latency-sensitive scenarios.[32]
Configuration in ASP.NET Core relies on the IConfiguration interface, with appsettings.json serving as the primary JSON-based provider for storing key-value pairs and hierarchical data, loaded by default during host construction.[33] Environment-specific files such as appsettings.Development.json and appsettings.Production.json override base settings based on the IHostEnvironment.EnvironmentName, enabling tailored behaviors like detailed logging in development or optimized security in production.[33] These files support reload-on-change by default, allowing runtime updates without restarting the application.[33] For containerized hosting, ASP.NET Core integrates seamlessly with Docker, where applications are built into images using multi-stage Dockerfiles that include the .NET runtime and publish the app for efficient, portable deployment across cloud platforms.[34] The host's configuration providers ensure environment variables from Docker override JSON settings, supporting scalable orchestration with tools like Docker Compose or Kubernetes.[35]
The configured host initializes the web server, which then passes incoming requests to the middleware pipeline for processing.[23]
Middleware and Request Pipeline
In ASP.NET Core, the request pipeline is composed of a series of middleware components that form a chain of request delegates, allowing developers to process incoming HTTP requests and outgoing responses in a modular and extensible manner. Each middleware can perform operations before and after invoking the next delegate in the chain, enabling tasks such as authentication, logging, and routing without tightly coupling logic to specific handlers. The pipeline is constructed using anIApplicationBuilder instance, typically within the Configure method of the application's startup configuration, where middleware is registered in the order of execution.[36]
Requests traverse the pipeline sequentially from the first registered middleware to the last, with the invocation order reversing during the response phase to allow post-processing, such as adding headers or compressing content. Middleware is added using extension methods like app.Use(), which passes control to the next component via a RequestDelegate parameter (often named next), or app.Run(), which terminates the chain without invoking further delegates. Short-circuiting occurs when a middleware fully handles the request—such as serving a static file—preventing propagation to subsequent components, which optimizes performance by avoiding unnecessary processing.[36]
ASP.NET Core includes a variety of built-in middleware for common scenarios, each with recommended placement to ensure correct functionality. For instance, UseAuthentication() authenticates users and populates HttpContext.User, and should precede any middleware relying on the authenticated identity, such as UseAuthorization(), which enforces access policies immediately after authentication. Routing middleware, added via UseRouting() and UseEndpoints(), matches requests to endpoints and constrains routes, typically positioned after authentication but before terminal middleware like MVC handlers. Error handling is facilitated by UseExceptionHandler() or the broader UseDeveloperExceptionPage() in development environments, both of which should be early in the pipeline to capture exceptions from downstream components. Other examples include UseStaticFiles() for serving assets, which acts as a terminal middleware for matching files, and UseHttpsRedirection() to enforce secure connections before URL-dependent logic. The order is critical; for example, UseCors() must precede caching middleware due to compatibility constraints.[36]
Customization of the pipeline allows developers to inject application-specific logic by creating custom middleware, either as inline delegates or reusable classes. Convention-based middleware uses a constructor accepting dependencies and an InvokeAsync or Invoke method taking HttpContext and RequestDelegate next, invoked via app.UseMiddleware<CustomMiddleware>(). For stronger typing and per-request activation, factory-based middleware implements the IMiddleware interface, which defines an InvokeAsync method and enables dependency injection of scoped services directly into the instance, registered via services.AddTransient<IMiddleware, CustomMiddleware>() and added with app.UseMiddleware<IMiddleware>(). This approach supports better testability and integration with the service container compared to convention-based methods.[37][38]
Branching enables conditional pipeline execution without duplicating components. The MapWhen() method creates a side branch based on a predicate (e.g., checking query strings or headers), executing a separate IApplicationBuilder configuration for matching requests while allowing non-matching ones to continue on the main path. For path-based branching, Map() routes specific segments (e.g., /admin) to isolated sub-pipelines. These features support scenarios like health checks or API versioning, where MapWhen can isolate endpoints without affecting the primary flow.[36]
Starting with .NET 6, the minimal hosting model simplifies pipeline configuration through WebApplication.CreateBuilder(), which automatically registers essential services and middleware, including endpoint routing that wraps the entire chain to eliminate explicit UseRouting() and UseEndpoints() calls in many cases. This evolution reduces boilerplate code while maintaining extensibility, allowing developers to focus on application logic rather than infrastructure setup.[25]
Key Components
MVC and Razor Pages
ASP.NET Core MVC implements the Model-View-Controller (MVC) design pattern, which separates an application into three interconnected components to promote separation of concerns and maintainability.[39] Models represent the data and business logic of the application, encapsulating domain-specific information and operations without direct ties to the user interface.[39] Views handle the presentation layer, rendering the user interface based on data from the models, typically using the Razor view engine to generate dynamic HTML.[40] Controllers act as intermediaries, processing incoming HTTP requests, interacting with models to retrieve or update data, and selecting appropriate views to render responses.[39] In MVC, controllers are classes that inherit fromController or ControllerBase and contain action methods decorated with attributes to define their behavior. For instance, the [Route] attribute specifies URL patterns for routing, while [HttpGet] and [HttpPost] restrict actions to specific HTTP methods, enabling precise control over request handling.[41] This attribute routing allows developers to define routes directly on controllers and actions, providing flexibility for complex URL structures compared to traditional patterns.[41]
Razor Pages offer a page-based programming model in ASP.NET Core, suited for simpler web applications where the focus is on individual pages rather than a full MVC separation.[42] Unlike MVC, Razor Pages do not require separate controllers; instead, each page combines the view and its logic in a single unit, reducing boilerplate for page-centric scenarios.[42] The @page directive, placed at the top of a .cshtml file, designates it as a Razor Page and enables direct routing to that file, with optional parameters for custom paths such as @page "/custom/path".[42] The associated PageModel class, typically in a companion .cshtml.cs file, contains the page's logic, including handler methods like OnGet for initializing data on GET requests and OnPost for processing form submissions on POST requests.[42]
Razor templating, shared between MVC views and Razor Pages, uses a syntax that embeds server-side C# code within HTML to generate dynamic content.[43] Directives such as @model declare the type of data passed to the view or page for strong typing, while @inject introduces dependency injection services directly into the markup for accessing shared resources.[43] Tag Helpers provide an HTML-friendly alternative to traditional HTML Helpers, allowing intuitive enhancements like <form asp-action="Submit"> to automatically generate action-specific forms, whereas HTML Helpers rely on method calls such as Html.BeginForm() for similar functionality.[44] Partial views enable reusable UI components invoked via @await Html.PartialAsync("PartialName"), and layouts, defined in files like _Layout.cshtml, establish a common structure across pages with placeholders for content sections.[45]
Routing in both MVC and Razor Pages supports convention-based and attribute-based approaches to map URLs to handlers.[46] Convention-based routing uses default patterns, such as {controller}/{action}/{id?} for MVC or file paths in the /Pages folder for Razor Pages, configured globally in the application startup.[41][42] Attribute-based routing, applied via [Route] attributes or @page parameters, offers granular control, including constraints like {id:int} for parameter validation.[41][42] For larger applications, areas in MVC organize code into functional modules, each with dedicated folders for controllers, views, and models under /Areas/{AreaName}, incorporating an area route parameter like {area:exists}/{controller}/{action} to isolate routing namespaces.[47] This structure facilitates scalability by allowing independent development of app sections while maintaining clean URL hierarchies.[47]
Web API and Minimal APIs
ASP.NET Core enables the development of RESTful web APIs through two primary approaches: controller-based Web APIs and Minimal APIs. Controller-based Web APIs leverage classes that inherit fromControllerBase, providing a structured way to handle HTTP requests and responses without view rendering support.[48] In contrast, Minimal APIs offer a lightweight alternative for defining endpoints with minimal boilerplate, introduced in .NET 6 to streamline API creation for microservices and high-throughput scenarios.[49] Both paradigms support core HTTP methods and integrate seamlessly with the framework's routing system, which is API-oriented and akin to MVC routing but focused on data exchange rather than page rendering.[41]
Web API controllers are implemented as classes deriving from ControllerBase, allowing actions to process requests and return results via IActionResult implementations such as Ok() for successful responses (HTTP 200) or NotFound() for missing resources (HTTP 404).[50] These actions can return domain objects directly, with ASP.NET Core handling serialization, or explicit results for finer control over status codes and headers.[50] Content negotiation is built-in, automatically selecting formats like JSON or XML based on client headers, configurable via input/output formatters or attributes such as [Produces("application/json")] and [Consumes("application/xml")] to enforce specific media types.[48]
Minimal APIs simplify endpoint definition using extension methods on the WebApplication instance, such as app.MapGet("/weatherforecast", () => forecasts) for GET requests or app.MapPost("/weatherforecast", (WeatherForecast forecast) => { /* logic */ }) for POST operations with parameter binding.[51] They support typed parameters, including route values (e.g., {id}), query strings, and body deserialization, as well as filters for cross-cutting concerns like authorization and exception handling.[51] Integration with OpenAPI is facilitated through built-in attributes or packages, enabling automatic documentation generation for tools like Swagger UI.[52]
API conventions in ASP.NET Core promote consistency by applying shared behaviors across controllers or actions, such as default response types and status codes, via the ApiConventionMethodAttribute or assembly-level ApiConventionTypeAttribute referencing DefaultApiConventions.[53] The [ApiController] attribute, applied to controllers, activates API-specific features including automatic model validation that returns HTTP 400 with ValidationProblemDetails if ModelState is invalid, along with inference of response types for OpenAPI generation.[48] For versioning, route constraints can be used to segment endpoints (e.g., /api/v1/products vs. /api/v2/products), ensuring backward compatibility without built-in framework enforcement.[41] Swagger/OpenAPI documentation is commonly generated using the Swashbuckle.AspNetCore package, which scans controllers or minimal endpoints to produce interactive UI and JSON schemas, configurable in Program.cs with builder.Services.AddSwaggerGen(); and app.UseSwagger(); app.UseSwaggerUI();.[54]
Performance-wise, Minimal APIs exhibit lower overhead than controller-based APIs due to reduced reflection and instantiation costs, making them suitable for microservices and high-volume endpoints, as evidenced by framework benchmarks showing faster startup and request throughput.[55] JSON serialization defaults to System.Text.Json, a high-performance, UTF-8-based library integrated into ASP.NET Core since .NET Core 3.0, which minimizes allocations and supports source generation for even greater efficiency in API responses.[56] Controller-based APIs, while slightly more resource-intensive, provide richer extensibility for complex scenarios without compromising overall framework speed.[55]
Features
Cross-Platform and Performance Capabilities
ASP.NET Core is designed as a cross-platform framework, leveraging the .NET runtime to enable development and deployment on Windows, Linux, and macOS without requiring platform-specific modifications to the application code.[9][13] This portability is facilitated by the cross-platform .NET SDK and the dotnet CLI, a unified command-line toolchain that supports creating, building, testing, and publishing applications across operating systems from a single codebase.[57] Developers can deploy ASP.NET Core applications to major cloud platforms such as Azure App Service, AWS Elastic Beanstalk, and Google Cloud App Engine using standard publishing workflows, often without altering the source code, as the framework abstracts underlying infrastructure differences.[58][59] Key performance capabilities in ASP.NET Core include Ahead-of-Time (AOT) compilation, introduced in .NET 7 and enhanced in subsequent releases, which compiles applications to native code ahead of runtime execution, resulting in faster startup times and reduced binary sizes compared to just-in-time (JIT) compilation.[60] The framework's default web server, Kestrel, supports the HTTP/3 protocol starting from .NET 7, enabled by default from .NET 8, enabling lower-latency connections over QUIC for improved throughput in modern networks.[27] Additionally, in-memory caching via the IMemoryCache interface allows efficient storage and retrieval of frequently accessed data within the application's memory, minimizing database round-trips and enhancing response times for read-heavy workloads.[61] Optimizations such as source generators further aid performance by enabling trimming of unused code during publishing, which reduces application footprint and deployment overhead.[62] In independent benchmarks like TechEmpower Framework Benchmarks, ASP.NET Core consistently ranks at the top for throughput, processing over 7 million requests per second in plaintext scenarios on optimized hardware, outperforming many popular web frameworks due to its efficient runtime and serverless-friendly design.[18][13] Recent advancements include Native AOT support for ASP.NET Core in .NET 9, tailored for cloud-native environments with minimal runtime dependencies, enabling sub-second startup in containerized and serverless deployments while maintaining compatibility with core features like Minimal APIs.[63]Security and Dependency Injection
ASP.NET Core includes a built-in dependency injection (DI) container that implements the Inversion of Control (IoC) pattern to manage object lifetimes and resolve dependencies across the application. Services are registered using theIServiceCollection interface in the Program.cs file or Startup.cs (in older versions), where developers can specify service lifetimes such as singleton, scoped, or transient via methods like AddSingleton, AddScoped, and AddTransient. For instance, a database context might be registered as scoped to ensure a new instance per HTTP request, promoting testability and reducing tight coupling between components.[64][65]
Constructor injection is the primary mechanism for providing dependencies to controllers, Razor pages, and other services, where the runtime resolves and injects required services automatically. This approach aligns with DI best practices by making dependencies explicit and facilitating unit testing through mocking. Additionally, the options pattern allows configuration data to be bound to strongly typed classes, registered via services.Configure<T>(configuration.GetSection("T")), enabling centralized and type-safe access to settings like connection strings or API keys.[64][66][67]
Security in ASP.NET Core is integrated through middleware and built-in APIs that handle authentication, authorization, and data protection, ensuring applications can enforce secure access controls. Authentication middleware supports multiple schemes, including cookie-based authentication for web apps and JSON Web Token (JWT) bearer authentication configured via AddAuthentication and AddJwtBearer extensions, which validate tokens against issuers, audiences, and signatures. For JWT, developers specify options like the authority URL and token validation parameters to secure API endpoints against unauthorized access. Authorization builds on authentication using policies and attributes like [Authorize], allowing role-based or claim-based checks, such as requiring specific roles via AddAuthorization(options => options.AddPolicy("Admin", policy => policy.RequireRole("Admin"))) to restrict actions.[68][69][70]
The data protection API provides cryptographic services for encrypting sensitive data, such as cookies or temporary tokens, using algorithms like AES with key management and rotation handled automatically. Keys are persisted to secure stores like file systems or Azure Key Vault, and the API generates unique protectors for different purposes to prevent misuse. This system addresses OWASP Top 10 risks like cryptographic failures (A02:2021) by ensuring robust encryption without requiring developers to manage low-level crypto primitives.[71][72][73]
Additional protections include HTTPS redirection middleware (UseHttpsRedirection) to enforce secure connections, preventing man-in-the-middle attacks as per OWASP A05:2021 security misconfigurations. Cross-Origin Resource Sharing (CORS) is configured via AddCors to allow controlled cross-domain requests, mitigating unauthorized access from external origins while adhering to browser security policies. Anti-forgery tokens, enabled with AddAntiforgery and validated using [ValidateAntiForgeryToken], protect against cross-site request forgery (CSRF, OWASP A01:2021 broken access control) by requiring unique tokens in POST requests. Rate limiting, introduced in .NET 7 via AddRateLimiter and middleware like UseRateLimiter, implements algorithms such as fixed-window or token bucket to throttle requests, defending against denial-of-service (DoS) attacks and brute-force attempts (OWASP A07:2021 identification and authentication failures).[74][75][76]
Best practices for security emphasize secrets management and auditing to maintain compliance and detect issues. Sensitive values like connection strings are stored using the secrets manager in development (dotnet user-secrets) and integrated with Azure Key Vault in production via the configuration provider (AddAzureKeyVault), which retrieves secrets securely without embedding them in code or appsettings files, aligning with OWASP A05:2021. Auditing is facilitated through the built-in ILogger interface, injected via DI, where developers log security events like login attempts or policy failures at appropriate levels (e.g., LogInformation for successes, LogWarning for suspicious activity) to enable monitoring and forensics. Structured logging with scopes, such as using (_logger.BeginScope(new Dictionary<string, object> { ["UserId"] = userId })), enhances traceability without performance overhead.[77][78][79]