ASP.NET CoreIHostedServiceBackgroundServiceBackground Tasks
IHostedService defines a service with `StartAsync` and `StopAsync` for long-running tasks. BackgroundService is an abstract base class implementing `IHostedService`, simplifying task execution with `ExecuteAsync`. Use `BackgroundService` for simpler background tasks. Example:
public class MyBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("Running...");
await Task.Delay(1000, stoppingToken);
}
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService();
}
ASP.NET CoreMiddlewareCustom Middleware
Middleware lifecycle events include request processing (`Invoke` or `InvokeAsync`) and optional initialization. Custom middleware is written by creating a class with an `InvokeAsync` method and registering it using `UseMiddleware` or as a delegate. Example:
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
await context.Response.WriteAsync("Custom Middleware\n");
await _next(context);
}
}
public static class CustomMiddlewareExtensions
{
public static IApplicationBuilder UseCustomMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware();
}
}
// Usage
app.UseCustomMiddleware();
ASP.NET CoreFiltersAuthorizationActionException
Filters execute code at specific pipeline stages. Authorization filters check access, Action filters run before/after actions, and Exception filters handle errors. Use filters for cross-cutting concerns like logging or authentication. Example:
public class CustomActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context) => Console.WriteLine("Before action");
public void OnActionExecuted(ActionExecutedContext context) => Console.WriteLine("After action");
}
[CustomActionFilter]
public class MyController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("Test");
}
ASP.NET CoreRequest PipelineCustomization
The request processing pipeline in ASP.NET Core is a series of middleware components that handle HTTP requests and responses. Each middleware can process the request, modify it, or pass it to the next middleware. The pipeline is configured in the `Configure` method using `IApplicationBuilder`. Customization is done by adding, removing, or reordering middleware using methods like `Use`, `Run`, or `Map`. Example:
MVC separates concerns into Models, Views, and Controllers, ideal for complex applications with reusable components. Razor Pages combines page logic and UI in a single file, simplifying page-focused apps. Use MVC for APIs or large apps; use Razor Pages for simpler, page-based applications like forms or dashboards. Example:
// MVC Controller
public class HomeController : Controller
{
public IActionResult Index() => View();
}
// Razor Page
@page
@model IndexModel
Hello, Razor Pages!
public class IndexModel : PageModel
{
public void OnGet() { }
}
ASP.NET CoreModel ValidationCustom Validators
Model validation uses data annotations or custom validation attributes to enforce rules. The framework checks `ModelState.IsValid` in controllers. Custom validators are created by inheriting from `ValidationAttribute`. Example:
public class CustomValidationAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value is string s && s.Length > 10)
return new ValidationResult("String too long");
return ValidationResult.Success;
}
}
public class MyModel
{
[CustomValidation]
public string Name { get; set; }
}
public class MyController : Controller
{
[HttpPost]
public IActionResult Create(MyModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
return Ok();
}
}
ASP.NET CoreLoggingLogging Providers
Logging is implemented using `ILogger` injected into classes. ASP.NET Core provides built-in logging with providers like Console, Debug, File, or third-party (e.g., Serilog). Configure providers in `appsettings.json` or `Program.cs`. Example:
public class MyController : ControllerBase
{
private readonly ILogger _logger;
public MyController(ILogger logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
_logger.LogInformation("Request received");
return Ok();
}
}
// Program.cs
builder.Services.AddLogging(logging => logging.AddConsole());
ASP.NET CoreEndpoint RoutingConventional Routing
Endpoint Routing (default in ASP.NET Core 3.0+) maps requests to endpoints explicitly, supporting middleware integration. Conventional Routing uses patterns (e.g., `{controller}/{action}`). Endpoint Routing is preferred for flexibility and middleware compatibility. Example:
ASP.NET CoreEnvironment ConfigurationConfiguration
Environment-specific configurations use `appsettings.{Environment}.json` files (e.g., `appsettings.Development.json`). The environment is set via `ASPNETCORE_ENVIRONMENT`. Example:
// appsettings.Development.json
{
"Settings": {
"Mode": "Dev"
}
}
public class MyController : ControllerBase
{
private readonly IConfiguration _config;
public MyController(IConfiguration config)
{
_config = config;
}
[HttpGet]
public IActionResult Get() => Ok(_config["Settings:Mode"]);
}
ASP.NET CoreSecurityJWT AuthenticationWeb API
Secure APIs using HTTPS, authentication (e.g., JWT, OAuth), authorization, CORS, and input validation. JWT Authentication uses tokens containing claims, validated via a secret key. Example:
Middleware operates in the request pipeline, handling all requests globally. Filters are MVC-specific, running at controller/action stages (e.g., authorization, action execution). Example:
// Middleware
app.Use(async (context, next) =>
{
await next();
});
// Filter
public class CustomFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context) { }
public void OnActionExecuted(ActionExecutedContext context) { }
}
ASP.NET CoreAuthorizationRole-basedPolicy-based
Role-based authorization checks user roles using `[Authorize(Roles = "Admin")]`. Policy-based authorization uses policies defined in `AuthorizationOptions` for complex requirements. Example:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthorization(options =>
{
options.AddPolicy("AdminOnly", policy => policy.RequireRole("Admin"));
});
}
public class MyController : ControllerBase
{
[Authorize(Policy = "AdminOnly")]
[HttpGet]
public IActionResult Get() => Ok("Admin access");
}
ASP.NET CoreStrongly-typed Configurationappsettings.json
Strongly-typed configurations map `appsettings.json` to C# classes using the Options pattern. Bind using `Configure` and access via `IOptions`. Example:
public class MySettings
{
public string ApiKey { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure(Configuration.GetSection("MySettings"));
}
public class MyController : ControllerBase
{
private readonly MySettings _settings;
public MyController(IOptions options)
{
_settings = options.Value;
}
[HttpGet]
public IActionResult Get() => Ok(_settings.ApiKey);
}
ASP.NET CoreDependency InjectionControllersMiddleware
Dependency Injection (DI) provides dependencies to classes, reducing coupling. In ASP.NET Core, services are registered in `ConfigureServices` and injected via constructors. Example:
public interface IMyService { string GetData(); }
public class MyService : IMyService { public string GetData() => "Data"; }
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped();
}
public class MyController : ControllerBase
{
private readonly IMyService _service;
public MyController(IMyService service) => _service = service;
[HttpGet]
public IActionResult Get() => Ok(_service.GetData());
}
ASP.NET CoreAPI VersioningWeb API
API versioning is supported via packages like `Microsoft.AspNetCore.Mvc.Versioning`, using URL paths, query strings, or headers. Example:
public void ConfigureServices(IServiceCollection services)
{
services.AddApiVersioning(options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
});
}
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok("Version 1");
}
ASP.NET CoreWeb APICreateConsume
Create a Web API using controllers or Minimal APIs. Consume it using `HttpClient` or tools like Postman. Example:
// API Controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get() => Ok(new[] { "Product1", "Product2" });
}
// Consuming with HttpClient
public async Task GetProducts(HttpClient client)
{
return await client.GetFromJsonAsync("api/products");
}
ASP.NET CoreHttpClientFactoryHTTP Requests
HttpClientFactory manages `HttpClient` instances, handling lifetime, DNS refresh, and resource cleanup. It’s recommended to avoid socket exhaustion and improve performance. Example:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("MyApi", client =>
{
client.BaseAddress = new Uri("https://api.example.com/");
});
}
public class MyService
{
private readonly HttpClient _client;
public MyService(IHttpClientFactory factory)
{
_client = factory.CreateClient("MyApi");
}
public async Task GetData() => await _client.GetStringAsync("/data");
}
ASP.NET CoreTestingUnit TestsIntegration Tests
Unit tests mock dependencies using Moq. Integration tests use `WebApplicationFactory` to test controllers with a real HTTP client. Example:
// Unit Test with Moq
public class MyServiceTests
{
[Fact]
public void GetData_ReturnsData()
{
var mockService = new Mock();
mockService.Setup(s => s.GetData()).Returns("Test");
var controller = new MyController(mockService.Object);
var result = controller.Get();
Assert.Equal("Test", ((OkObjectResult)result).Value);
}
}
// Integration Test
public class MyControllerTests : IClassFixture>
{
private readonly WebApplicationFactory _factory;
public MyControllerTests(WebApplicationFactory factory) => _factory = factory;
[Fact]
public async Task Get_ReturnsData()
{
var client = _factory.CreateClient();
var response = await client.GetStringAsync("/api/my");
Assert.Equal("Test", response);
}
}
ASP.NET CoreIOptionsIOptionsSnapshotIOptionsMonitor
IOptions provides static configuration. IOptionsSnapshot reloads per request scope. IOptionsMonitor supports real-time updates and change notifications. Example:
public class MySettings
{
public string Value { get; set; }
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure(Configuration.GetSection("MySettings"));
}
public class MyController : ControllerBase
{
private readonly MySettings _settings;
public MyController(IOptionsSnapshot options)
{
_settings = options.Value;
}
[HttpGet]
public IActionResult Get() => Ok(_settings.Value);
}
ASP.NET CoreMinimal APIWeb API
Minimal APIs provide a simplified way to define endpoints without controllers, using `MapGet`, `MapPost`, etc. Use for lightweight APIs or microservices. Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello, Minimal API!");
app.MapPost("/data", (MyModel model) => $"Received {model.Name}");
app.Run();
public class MyModel
{
public string Name { get; set; }
}
ASP.NET CoreGlobal Exception HandlingError Management
Global exception handling uses middleware like `UseExceptionHandler` or custom exception filters to catch and process unhandled exceptions. Example:
Kestrel is a cross-platform web server for ASP.NET Core. Compared to IIS (Windows-only, feature-rich) and Nginx (high-performance reverse proxy), Kestrel is lightweight and fast but often used with a reverse proxy for production. Example:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseKestrel();
var app = builder.Build();
app.Run();
ASP.NET CoreStatic FilesAccess Control
Serve static files using `UseStaticFiles` from `wwwroot`. Restrict access with middleware or authorization. Example:
app.UseStaticFiles();
// Restrict with middleware
app.Use(async (context, next) =>
{
if (context.Request.Path.StartsWithSegments("/restricted"))
{
if (!context.User.Identity.IsAuthenticated)
{
context.Response.StatusCode = 401;
return;
}
}
await next();
});
ASP.NET CorePerformance Optimization
Improve performance by using caching (e.g., IMemoryCache), async/await, response compression, minimizing middleware, and optimizing database queries. Example:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
}
public void Configure(IApplicationBuilder app)
{
app.UseResponseCompression();
}
ASP.NET CoreCORSConfigurationSecurity
CORS is handled via middleware, allowing cross-origin requests. Configure using `AddCors` and `UseCors` with policies. Example: