MENU ACTIVE
05:02:43
QUICK ACTIONS
SYS.PORTFOLIO.001v3.7.2
HOME/BLOG/ASP.NET Core 6: Building Modern Web APIs
Backend
1/20/202511 min readBy Hypynnax

ASP.NET Core 6: Building Modern Web APIs

Learn how to build robust, scalable Web APIs with ASP.NET Core 6, covering authentication, documentation, and best practices.

#ASP.NET Core#C##Web API#REST#Authentication

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:

EXAMPLE CODE
dotnet new webapi -n MyApi
cd MyApi
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

Creating RESTful Endpoints

Define clean API endpoints:

EXAMPLE CODE
[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:

EXAMPLE CODE
// 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:

EXAMPLE CODE
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:

EXAMPLE CODE
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:

EXAMPLE CODE
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.

H
Hypynnax
SOFTWARE ENGINEER
UPDATED1/20/2025