Introduction
ASP.NET Core 6 provides a powerful framework for building modern Web APIs. Let's explore how to create production-ready APIs with best practices.
Project Setup
Create a new Web API project:
dotnet new webapi -n MyApi
cd MyApi
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearerCreating RESTful Endpoints
Define clean API endpoints:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
var products = await _productService.GetAllAsync();
return Ok(products);
}
[HttpPost]
public async Task<ActionResult<Product>> CreateProduct(ProductDto productDto)
{
var product = await _productService.CreateAsync(productDto);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
}Authentication & Authorization
Implement JWT authentication:
// Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
};
});
// Controller
[Authorize]
[HttpGet("protected")]
public IActionResult GetProtectedData()
{
return Ok("This is protected data");
}API Versioning
Implement API versioning:
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsV1Controller : ControllerBase { }
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsV2Controller : ControllerBase { }Swagger Documentation
Configure Swagger UI:
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My API",
Version = "v1",
Description = "A comprehensive API for product management"
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
});Error Handling
Implement global exception handling:
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;return context.Response.WriteAsync(new ErrorDetails { StatusCode = context.Response.StatusCode, Message = "Internal Server Error" }.ToString()); } } ```
Performance Tips
Optimize your API:
- ▹Use async/await for I/O operations
- ▹Implement caching with IMemoryCache
- ▹Use pagination for large datasets
- ▹Enable response compression
- ▹Profile with Application Insights
Conclusion
ASP.NET Core 6 provides excellent tools for building modern APIs. Following these patterns ensures your APIs are secure, scalable, and maintainable.