ASP.NET Core 8 Web API performance optimization illustration with API cloud and speedometer showing maximum performance

How to Optimize ASP.NET Core 8 Web API Performance (Best Practices Guide)

Why Performance Optimization Matters In ASP.NET Core 8 Web API performance

// Bad example: returning all users
[HttpGet("users")]
public async Task<IActionResult> GetUsers()
{
    var users = await _context.Users.ToListAsync();
    return Ok(users);
}

Techniques for Optimizing Performance of Application In ASP.NET Core 8 Web API performance

1. Enable Response Caching

// Program.cs
builder.Services.AddResponseCaching();
app.UseResponseCaching();

app.MapGet("/products", async (AppDbContext db) =>
{
    var products = await db.Products.AsNoTracking().ToListAsync();
    return Results.Ok(products);
}).CacheOutput();

2. Use Asynchronous Programming (async / await)

// Bad: blocks thread
[HttpGet("orders")]
public IActionResult GetOrders()
{
    var orders = _context.Orders.ToList(); 
    return Ok(orders);
}

// Good: async call
[HttpGet("orders")]
public async Task<IActionResult> GetOrders()
{
    var orders = await _context.Orders.ToListAsync();
    return Ok(orders);
}

3. Optimize Database Queries (EF Core Best Practices)


// Bad: returns all columns
var users = await _context.Users.ToListAsync();

// Good: return only needed columns
var users = await _context.Users
    .Select(u => new { u.Id, u.Name, u.Email })
    .AsNoTracking()
    .ToListAsync();

// Avoid N+1 queries
var usersWithOrders = await _context.Users
    .Include(u => u.Orders)
    .ToListAsync();

4. Enable Response Compression

// 1. Enable response compression services
builder.Services.AddResponseCompression();

// 2. Activate the middleware in the app pipeline
app.UseResponseCompression();

// 3. Define an API endpoint that returns a list of products
app.MapGet("/products", async (AppDbContext db) =>
{
    // Fetch all products from the database
    var products = await db.Products.ToListAsync();
    
    // Return the data to the client
    // The middleware automatically compresses the JSON using Brotli or Gzip
    return Results.Ok(products);
});
GET /products HTTP/1.1
Host: example.com
Accept-Encoding: br, gzip
HTTP/1.1 200 OK
Content-Encoding: br
Content-Type: application/json

5. Use Logging

// 1️⃣ Configure Serilog at the start of your application
Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()       // Output logs to console
    .WriteTo.File("logs.txt") // Optional: save logs to a file
    .MinimumLevel.Information() // Only log Information and above
    .CreateLogger();

// 2️⃣ API endpoint using structured logging
app.MapGet("/products", async (AppDbContext db, ILogger<Program> logger) =>
{
    var userId = 123; // Example user ID

    // Log the request
    logger.LogInformation("User {UserId} requested products at {Time}", userId, DateTime.UtcNow);

    // Fetch products from database
    var products = await db.Products.ToListAsync();

    return Results.Ok(products);
});
[Information] User 123 requested products at 2026-03-01T10:15:00Z

6. Minimize Middleware Overhead

app.UseAuthentication();    // runs first
app.UseAuthorization();     // runs second
app.UseCustomLogging();     // runs third
app.UseStaticFiles();       // runs last
app.UseStaticFiles();       // serve CSS/JS first
app.UseAuthentication();    // then handle user authentication
app.UseAuthorization();     // then authorization
app.UseCustomLogging();     // log only relevant requests

7. Use Pagination Instead of Returning Large Data

app.MapGet("/products", async (AppDbContext db, int page = 1, int pageSize = 20) =>
{
    // Skip items for previous pages and take only the page size
    var products = await db.Products
        .Skip((page - 1) * pageSize)
        .Take(pageSize)
        .ToListAsync();

    return Results.Ok(products);
});

8. Enable Rate Limiting

builder.Services.AddRateLimiter(options =>
{
    options.AddFixedWindowLimiter("default", opt =>
    {
        opt.PermitLimit = 100; // Maximum 100 requests
        opt.Window = TimeSpan.FromMinutes(1); // Per 1 minute
    });
});

Conclusion

Recommended Next Reads

🚀 Subscribe for Tech Updates

📧

👤

We respect your privacy. Unsubscribe anytime.