Adding Swagger (OpenAPI) Documentation to Azure Functions — .NET 8 Isolated Worker Model

Author: Jayakumar Srinivasan

Estimated Reading Time: 8 minutes

1. Introduction: Why Swagger Matters for Azure Functions

Most enterprises today rely heavily on Azure Functions to power their API and integration ecosystem.
However, as the number of functions grows, one challenge becomes painfully clear — discoverability.

Internal teams — developers, QA, and integration engineers — often struggle to understand:

  • What endpoints exist?
  • What payload formats are expected?
  • How should they test integrations before backend availability?

Traditionally, Swagger (OpenAPI) solved this for Web APIs — but when it came to Azure Functions, documentation was either manual or non-existent.

This article walks through how we solved this in our enterprise by enabling Swagger documentation for Azure Functions built on the Isolated Worker Model (.NET 8) using Swashbuckle and OpenAPI attributes.


2. Understanding the Azure Function Isolated Worker Model

With .NET 8, the Isolated Worker Model has become the recommended way to build Azure Functions.

It runs your code out of process from the Azure Functions runtime, giving you:

  • Full control over dependency injection
  • Custom middleware
  • Richer debugging experience
  • Compatibility with standard ASP.NET middleware and OpenAPI extensions

If you’ve migrated from the in-process model, you’ll quickly realize that the default OpenAPI integration no longer applies.
That’s exactly where Swashbuckle bridges the gap.


3. Required NuGet Packages

Install the following packages from NuGet:

Microsoft.Azure.Functions.Worker.Extensions.OpenApi

💡 Note: The Microsoft.Azure.Functions.Worker.Extensions.OpenApi package adds the OpenAPI binding attributes, while Swashbuckle.AspNetCore provides the Swagger generation capabilities.

4. Annotating Your Azure Function with OpenAPI Attributes

Here’s a sample Azure Function showcasing OpenAPI annotations:

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes;
using Microsoft.OpenApi.Models;

public class CustomerFunctions
{
    [Function("GetCustomerById")]
    [OpenApiOperation(operationId: "GetCustomerById", tags: new[] { "Customer" })]
    [OpenApiParameter(name: "id", In = ParameterLocation.Path, Required = true, Type = typeof(string), Description = "The Customer ID")]
    [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "application/json", bodyType: typeof(Customer), Description = "Customer details")]
    public HttpResponseData Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", Route = "customer/{id}")] HttpRequestData req, 
        string id)
    {
        var response = req.CreateResponse(HttpStatusCode.OK);
        var customer = new Customer { Id = id, Name = "John Doe", Country = "Sweden" };
        response.WriteAsJsonAsync(customer);
        return response;
    }
}

public class Customer
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Country { get; set; }
}

🧠 Tip: You can apply the [OpenApiRequestBody], [OpenApiResponseWithBody], and [OpenApiParameter] attributes to define schema and descriptions just like in traditional ASP.NET Core APIs.

5. Hosting Swagger UI in Azure Functions

Once configured, you can navigate to:

https://<your-function-app>.azurewebsites.net/api/swagger/ui

Please be aware that you need to enable CORS on the Function to view the swagger documentation. There are many ways to secure your Swagger docuentation which will bea a separate article and I will not discuss much about it here. However using CORS in PROD environment should be avoided.

You’ll see a fully interactive Swagger UI showing:

  • All function endpoints
  • Input/output parameters
  • Response models
  • Sample payloads

6. Real-world Benefits We Observed

After implementing Swagger documentation for our Azure Function ecosystem:

  • 70% fewer API-related support tickets
  • Faster onboarding for new developers and QA engineers
  • Zero dependency on manually shared Postman collections
  • Instant clarity for consuming systems and teams

This approach simplified not just documentation — it enhanced collaboration, maintainability, and confidence across teams.


7. Lessons Learned and Best Practices

  1. Keep your OpenAPI annotations consistent across functions.
  2. Always version your APIs and reflect them in Swagger tags.
  3. Automate your Swagger JSON publishing during CI/CD so that documentation is always fresh.
  4. Add OpenAPI authentication if your environment demands security compliance.

8. Summary

Enabling Swagger for Azure Functions in the Isolated Worker Model may seem like a small addition — but it changes how teams understand and consume APIs.

By embedding discoverability directly into the function, you empower everyone — developers, testers, and architects alike — to work with clarity.

“True scalability isn’t about building more APIs — it’s about helping people use them better.”

Mastering Entity Framework Core: Advanced Features Uncovered with Real-Time scenarios

Entity Framework (EF) has been a cornerstone for .NET developers, providing a robust ORM (Object-Relational Mapping) framework to interact with databases using .NET objects. While many developers are familiar with the basics, there are several lesser-known tricks and best practices that can significantly enhance your EF experience. In this article, we will explore some of these hidden gems and also highlight new features introduced in the latest version of Entity Framework Core (EF Core 6.0 and EF Core 7.0).

Leveraging Global Query Filters

Real-Time Scenario

Imagine you are developing a multi-tenant application where each tenant should only see their own data. Implementing this manually in every query can be error-prone and cumbersome.

Feature Explanation

Global Query Filters, introduced in EF Core 2.0, allow you to define filters that apply to all queries for a given entity type. This is particularly useful for implementing multi-tenancy, soft deletes, or any scenario where you need to filter data globally.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>()
        .HasQueryFilter(c => !c.IsDeleted);
} 

Table Schema

SQL Script

CREATE TABLE Customers (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100),
    IsDeleted BIT
);

Table Format

Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the customer
IsDeletedBITIndicates if the customer is deleted

Using Value Conversions

Real-Time Scenario

Suppose you have a custom type for representing monetary values in your domain model, but you need to store these values as decimals in the database.

Feature Explanation

Value Conversions, introduced in EF Core 2.1, enable you to map custom types to database types. This is useful when you have domain-specific types that need to be stored in a database-friendly format.

public class Money
{
    public decimal Amount { get; set; }
    public string Currency { get; set; }

    public override string ToString() => $"{Amount} {Currency}";
    public static Money Parse(string value)
    {
        var parts = value.Split(' ');
        return new Money { Amount = decimal.Parse(parts[0]), Currency = parts[1] };
    }
}

modelBuilder.Entity<Order>()
    .Property(o => o.TotalAmount)
    .HasConversion(
        v => v.ToString(), // Convert to string for storage
        v => Money.Parse(v) // Convert back to custom type
    );  

Table Schema

SQL Script

CREATE TABLE Orders (
    Id INT PRIMARY KEY,
    CustomerId INT,
    TotalAmount NVARCHAR(50),
    FOREIGN KEY (CustomerId) REFERENCES Customers(Id)
);
    

Table Format

Column NameData TypeDescription
IdINTPrimary key
CustomerIdINTForeign key to Customers table
TotalAmountNVARCHAR(50)Custom monetary value stored as string

Compiled Queries for Performance

Real-Time Scenario

You have a high-traffic application where certain queries are executed frequently, and you need to optimize performance to handle the load.

Feature Explanation

Compiled Queries, introduced in EF Core 2.0, can significantly improve the performance of frequently executed queries by pre-compiling the query plan.

private static readonly Func<YourDbContext, int, Customer> _compiledQuery =
    EF.CompileQuery((YourDbContext context, int id) =>
        context.Customers.Single(c => c.Id == id));

public Customer GetCustomerById(int id)
{
    return _compiledQuery(_context, id);
}
    

Table Schema

SQL Script

CREATE TABLE Customers (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100)
);   

Table Format

Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the customer

Interceptors for Advanced Scenarios

Real-Time Scenario

You need to implement custom logging for all database commands executed by your application to comply with auditing requirements.

Feature Explanation

Interceptors, introduced in EF Core 3.0, allow you to hook into various stages of EF’s operation, such as command execution, saving changes, and more. This is useful for logging, auditing, or modifying behavior dynamically.

public class MyCommandInterceptor : DbCommandInterceptor
{
    public override InterceptionResult<int> NonQueryExecuting(
        DbCommand command, CommandEventData eventData, InterceptionResult<int> result)
    {
        // Log or modify the command here
        return base.NonQueryExecuting(command, eventData, result);
    }
}

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.AddInterceptors(new MyCommandInterceptor());
}
    

Table Schema

No specific schema changes are required for interceptors.

Temporal Tables for Historical Data

Real-Time Scenario

Your application needs to maintain a history of changes to certain entities for auditing and compliance purposes.

Feature Explanation

Temporal Tables, supported by EF Core 6.0, allow you to track changes to your data over time. This is useful for auditing and historical analysis.

modelBuilder.Entity<Customer>()
    .ToTable("Customers", b => b.IsTemporal());
    

Table Schema

SQL Script

CREATE TABLE Customers (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100),
    ValidFrom DATETIME2 GENERATED ALWAYS AS ROW START,
    ValidTo DATETIME2 GENERATED ALWAYS AS ROW END,
    PERIOD FOR SYSTEM_TIME (ValidFrom, ValidTo)
) WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE = dbo.CustomersHistory));
    

Table Format

Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the customer
ValidFromDATETIME2Start of the validity period
ValidToDATETIME2End of the validity period

New Features in the Latest Entity Framework

a. Many-to-Many Relationships

Real-Time Scenario

You are developing a library management system where books can have multiple authors, and authors can write multiple books. Modeling this relationship manually can be tedious.

Feature Explanation

The latest version of EF Core (EF Core 5.0) introduces native support for many-to-many relationships without needing a join entity.

modelBuilder.Entity<Author>()
    .HasMany(a => a.Books)
    .WithMany(b => b.Authors);
    

Table Schema

SQL Script
CREATE TABLE Authors (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100)
);

CREATE TABLE Books (
    Id INT PRIMARY KEY,
    Title NVARCHAR(100)
);

CREATE TABLE AuthorBook (
    AuthorId INT,
    BookId INT,
    PRIMARY KEY (AuthorId, BookId),
    FOREIGN KEY (AuthorId) REFERENCES Authors(Id),
    FOREIGN KEY (BookId) REFERENCES Books(Id)
);
    
Table Format
Authors Table
Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the author
Books Table
Column NameData TypeDescription
IdINTPrimary key
TitleNVARCHAR(100)Title of the book
AuthorBook Table
Column NameData TypeDescription
AuthorIdINTForeign key to Authors table
BookIdINTForeign key to Books table

b. Improved LINQ Translation

Real-Time Scenario

You have complex LINQ queries that need to be translated into efficient SQL to ensure optimal performance.

Feature Explanation

EF Core 5.0 and later versions have improved their LINQ translation capabilities, allowing for more complex queries to be translated into efficient SQL.

CustomerIdINTForeign key to Customers tableTotalAmountNVARCHAR(50)Custom monetary value stored as string

c. Split Queries for Related Data

Real-Time Scenario

You need to load large datasets with related data without running into performance issues caused by the N+1 query problem.

Feature Explanation

Split Queries, introduced in EF Core 5.0, allow you to load related data in multiple queries, reducing the risk of the N+1 query problem and improving performance for large result sets.

var data = context.Customers
    .Include(c => c.Orders)
    .AsSplitQuery()
    .ToList();
    

Table Schema

SQL Script
CREATE TABLE Customers (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100)
);

CREATE TABLE Orders (
    Id INT PRIMARY KEY,
    CustomerId INT,
    TotalAmount NVARCHAR(50),
    FOREIGN KEY (CustomerId) REFERENCES Customers(Id)
);
    
Table Format
Customers Table
Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the customer
Orders Table
Column NameData TypeDescription
IdINTPrimary key
CustomerIdINTForeign key to Customers table
TotalAmountNVARCHAR(50)Custom monetary value stored as string

d. Savepoints for Transactions

Real-Time Scenario

You are performing a series of operations within a transaction and need to create intermediate points to roll back to in case of errors.

Feature Explanation

Savepoints, introduced in EF Core 7.0, allow you to create intermediate points within a transaction, providing more control over transaction management.

using var transaction = context.Database.BeginTransaction();
try
{
    // Perform some operations
    var savepoint = transaction.CreateSavepoint("BeforeCriticalOperation");

    // Perform critical operation
    transaction.RollbackToSavepoint("BeforeCriticalOperation");

    transaction.Commit();
}
catch
{
    transaction.Rollback();
}
    

Table Schema

No specific schema changes are required for savepoints.

e. Primitive Collections

Real-Time Scenario

You need to store a list of primitive values, such as strings or integers, directly within an entity without creating a separate table.

Feature Explanation

Primitive Collections, introduced in EF Core 6.0, allow you to store collections of primitive types directly within an entity.

public class Product
{
    public int Id { get; set; }
    public List<string> Tags { get; set; }
}

modelBuilder.Entity<Product>()
    .Property(p => p.Tags)
    .HasConversion(
        v => string.Join(',', v), // Convert list to comma-separated string
        v => v.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList() // Convert string back to list
    );
    

Table Schema

SQL Script
CREATE TABLE Products (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100),
    Tags NVARCHAR(MAX)
);
    
Table Format
Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the product
TagsNVARCHAR(MAX)Comma-separated list of tags

f. HierarchyId Support

Real-Time Scenario

You are working with hierarchical data, such as organizational structures or file systems, and need to efficiently manage and query this data.

Feature Explanation

HierarchyId support, introduced in EF Core 7.0, allows you to work with hierarchical data types in SQL Server.

public class Category
{
    public int Id { get; set; }
    public HierarchyId HierarchyId { get; set; }
}

modelBuilder.Entity<Category>()
    .Property(c => c.HierarchyId)
    .HasConversion(
        v => v.ToString(), // Convert HierarchyId to string for storage
        v => HierarchyId.Parse(v) // Convert string back to HierarchyId
    );
    

Table Schema

SQL Script
CREATE TABLE Categories (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100),
    HierarchyId HIERARCHYID
);
    
Table Format
Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the category
HierarchyIdHIERARCHYIDHierarchical data identifier

g. Efficient Bulk Operations

Real-Time Scenario

You need to perform bulk insert, update, or delete operations efficiently to handle large datasets.

Feature Explanation

Efficient Bulk Operations, supported by third-party libraries like EFCore.BulkExtensions, allow you to perform bulk operations with high performance.

context.BulkInsert(products);
context.BulkUpdate(products);
context.BulkDelete(products);
    

Table Schema

SQL Script
CREATE TABLE Products (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100)
);
    
Table Format
Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the product

h. JSON Column Enhancements

Real-Time Scenario

You need to store and query JSON data within your database, leveraging the flexibility of JSON columns.

Feature Explanation

JSON Column Enhancements, introduced in EF Core 6.0, provide improved support for storing and querying JSON data.

public class Customer
{
    public int Id { get; set; }
    public string JsonData { get; set; }
}

var query = context.Customers
    .Where(c => EF.Functions.JsonContains(c.JsonData, "{\"key\":\"value\"}"))
    .ToList();
    

Table Schema

SQL Script
CREATE TABLE Customers (
    Id INT PRIMARY KEY,
    Name NVARCHAR(100),
    JsonData NVARCHAR(MAX)
);
    
Table Format
Column NameData TypeDescription
IdINTPrimary key
NameNVARCHAR(100)Name of the customer
JsonDataNVARCHAR(MAX)JSON data stored as string
Sample JSON
{
    "key": "value",
    "nested": {
        "subkey": "subvalue"
    },
    "array": [1, 2, 3]
}
    

Conclusion

Entity Framework continues to evolve, offering powerful features and capabilities that can greatly enhance your data access layer. By leveraging these lesser-known tricks and best practices, you can write more efficient, maintainable, and robust code. Stay updated with the latest features and continuously explore the depths of EF to unlock its full potential.

Exploring New Features in .NET 9.0: A Comprehensive Guide

.NET 9.0 brings a host of new features and performance improvements that enhance the development experience and application performance. In this article, we’ll explore some key new features, including those rarely discussed in public forums, discuss the problem statements they address, how these issues were handled in older versions of .NET, and how .NET 9.0 provides a better solution. We’ll also delve into the performance improvements introduced in .NET 9.0.

.NET 9.0 continues to build on the foundation of previous versions, introducing new features and enhancements that make development more efficient and applications more performant. Let’s dive into some significant new features and the performance improvements in .NET 9.0.

Feature 1: Improved JSON Serialization

Problem Statement

In older versions of .NET, JSON serialization could be slow and cumbersome, especially for large and complex objects. Developers often had to rely on third-party libraries like Newtonsoft.Json to achieve better performance and flexibility.

Solution in Older Versions

In .NET Core 3.0 and later, System.Text.Json was introduced as a built-in JSON serializer, offering better performance than Newtonsoft.Json. However, it still had limitations in terms of flexibility and ease of use.

Solution in .NET 9.0

.NET 9.0 introduces significant improvements to System.Text.Json, including better performance, enhanced support for polymorphic serialization, and improved handling of circular references. These enhancements make JSON serialization faster and more flexible, reducing the need for third-party libraries.

Sample Code

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Program
{
    public static void Main()
    {
        var product = new Product { Id = 1, Name = "Laptop", Price = 999.99M };
        var options = new JsonSerializerOptions
        {
            WriteIndented = true,
            DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
        };

        string json = JsonSerializer.Serialize(product, options);
        Console.WriteLine(json);
    }

}

Real-World Implementation Scenario

In an e-commerce application, efficient JSON serialization is crucial for handling product data. With the improvements in System.Text.Json in .NET 9.0, developers can serialize and deserialize product information more efficiently, enhancing the application’s performance and user experience.

MSDN Reference: System.Text.Json in .NET 9.0

Feature 2: Enhanced HTTP/3 Support

Problem Statement

HTTP/3 is the latest version of the HTTP protocol, offering improved performance and security. However, support for HTTP/3 in older versions of .NET was limited, requiring developers to use workarounds or third-party libraries to take advantage of its benefits.

Solution in Older Versions

In .NET 5.0 and later, preliminary support for HTTP/3 was introduced, but it was not fully integrated, and developers faced challenges in configuring and using it effectively.

Solution in .NET 9.0

.NET 9.0 provides full support for HTTP/3, making it easier for developers to leverage the benefits of the latest HTTP protocol. This includes improved performance, reduced latency, and enhanced security features, all integrated seamlessly into the .NET framework.

Sample Code

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main()
    {
        var handler = new SocketsHttpHandler
        {
            EnableMultipleHttp2Connections = true
        };

        var client = new HttpClient(handler)
        {
            DefaultRequestVersion = new Version(3, 0)
        };

        HttpResponseMessage response = await client.GetAsync("https://example.com");
        string content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(content);
    }
}

Real-World Implementation Scenario

In a real-time communication application, such as a chat or video conferencing app, leveraging HTTP/3 can significantly reduce latency and improve data transfer speeds. With full support for HTTP/3 in .NET 9.0, developers can build more responsive and efficient communication applications.

MSDN Reference: HTTP/3 Support in .NET 9.0

Feature 3: New Data Annotations

Problem Statement

Data validation is a critical aspect of application development. In older versions of .NET, developers often had to create custom validation logic or use limited built-in Data Annotations, which could be cumbersome and error-prone.

Solution in Older Versions

Previous versions of .NET provided basic Data Annotations for common validation scenarios. However, for more complex validations, developers had to rely on custom validation logic or third-party libraries.

Solution in .NET 9.0

.NET 9.0 introduces new Data Annotations, including PhoneNumber, Url and CreditCard, which simplify validation logic and reduce the need for custom validators. These new annotations make it easier to enforce data integrity and improve code maintainability.

Sample Code

using System;
using System.ComponentModel.DataAnnotations;

public class User
{
    [Required(ErrorMessage = "Username is required.")]
    public string Username { get; set; }

    [EmailAddress(ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }

    [PhoneNumber(ErrorMessage = "Invalid phone number.")]
    public string Phone { get; set; }

    [Url(ErrorMessage = "Invalid URL.")]
    public string Website { get; set; }

    [CreditCard(ErrorMessage = "Invalid credit card number.")]
    public string CreditCardNumber { get; set; }

}

public class Program
{
    public static void Main()
    {
        var user = new User
        {
            Username = "johndoe",
            Email = "john.doe@example.com",
            Phone = "123-456-7890",
            Website = "https://example.com",
            CreditCardNumber = "4111111111111111"
        };

        var context = new ValidationContext(user, null, null);
        var results = new List<ValidationResult>();
        bool isValid = Validator.TryValidateObject(user, context, results, true);

        if (isValid)
        {
            Console.WriteLine("User is valid.");
        }
        else
        {
            foreach (var validationResult in results)
            {
                Console.WriteLine(validationResult.ErrorMessage);
            }
        }
    }
}

Real-World Implementation Scenario

In a user registration system, validating user input is essential to ensure data integrity and security. With the new Data Annotations in .NET 9.0, developers can easily enforce validation rules for user information, reducing the need for custom validation logic and improving code maintainability.

MSDN Reference: New Data Annotations in .NET 9.0

Feature 4: Source Generators Enhancements

Problem Statement

Source Generators, introduced in .NET 5.0, allow developers to generate source code during compilation. However, the initial implementation had limitations in terms of performance and ease of use.

Solution in Older Versions

In .NET 5.0 and .NET 6.0, Source Generators provided a way to generate code at compile time, but developers faced challenges with performance and integration into existing projects.

Solution in .NET 9.0

.NET 9.0 introduces enhancements to Source Generators, including improved performance, better integration with the build process, and more powerful APIs for generating code. These enhancements make it easier for developers to leverage Source Generators in their projects.

Sample Code

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(Product))]
public partial class ProductJsonContext : JsonSerializerContext
{
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Program
{
    public static void Main()
    {
        var product = new Product { Id = 1, Name = "Laptop", Price = 999.99M };
        string json = JsonSerializer.Serialize(product, ProductJsonContext.Default.Product);
        Console.WriteLine(json);
    }
}

Real-World Implementation Scenario

In a large-scale application with complex data models, Source Generators can automate the generation of boilerplate code, reducing development time and minimizing errors. With the enhancements in .NET 9.0, developers can more efficiently generate and manage code, improving overall productivity.

MSDN Reference: Source Generators in .NET 9.0

Feature 5: Improved AOT Compilation

Problem Statement

Ahead-of-Time (AOT) compilation can significantly improve application startup times and performance. However, AOT support in older versions of .NET was limited and often required complex configurations.

Solution in Older Versions

In .NET 6.0, AOT compilation was introduced, but it was primarily targeted at specific scenarios and required manual configuration.

Solution in .NET 9.0

.NET 9.0 enhances AOT compilation, making it more accessible and easier to configure. These improvements include better tooling support, simplified configuration, and broader applicability across different types of applications.

Sample Code

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <PublishAot>true</PublishAot>
  </PropertyGroup>
</Project>

Real-World Implementation Scenario

In performance-critical applications, such as financial trading platforms or real-time data processing systems, AOT compilation can significantly reduce startup times and improve runtime performance. With the enhancements in .NET 9.0, developers can more easily leverage AOT compilation to optimize their applications.

MSDN Reference: AOT Compilation in .NET 9.0

Performance Improvements in .NET 9.0

.NET 9.0 brings several performance improvements that enhance the overall efficiency of applications. Key areas of improvement include:

  1. JIT Compilation: Enhanced Just-In-Time (JIT) compilation results in faster startup times and improved runtime performance.
  2. Async/Await: Improved handling of asynchronous operations reduces overhead and enhances scalability.
  3. Networking: Optimized networking stack provides better throughput and lower latency for network-intensive applications.
  4. Garbage Collection (GC): Optimized GC algorithms reduce memory fragmentation and improve application responsiveness.

These performance enhancements make .NET 9.0 a compelling choice for developers looking to build high-performance applications.

MSDN Reference: Performance Improvements in .NET 9.0

Real-World Implementation Scenarios

E-Commerce Application

In an e-commerce application, efficient JSON serialization and validation are crucial for handling product data and user information. With the improvements in System.Text.Json and new Data Annotations in .NET 9.0, developers can build more efficient and maintainable applications.

Real-Time Communication Application

In a real-time communication application, leveraging HTTP/3 can significantly reduce latency and improve data transfer speeds. With full support for HTTP/3 in .NET 9.0, developers can build more responsive and efficient communication applications.

Large-Scale Enterprise Application

In a large-scale enterprise application with complex data models, Source Generators can automate the generation of boilerplate code, reducing development time and minimizing errors. With the enhancements in .NET 9.0, developers can more efficiently generate and manage code, improving overall productivity.

Performance-Critical Application

In performance-critical applications, such as financial trading platforms or real-time data processing systems, AOT compilation can significantly reduce startup times and improve runtime performance. With the enhancements in .NET 9.0, developers can more easily leverage AOT compilation to optimize their applications.

Conclusion

.NET 9.0 introduces a range of new features and performance improvements that make development more efficient and applications more performant. From improved JSON serialization and enhanced HTTP/3 support to new Data Annotations, Source Generators enhancements, and improved AOT compilation, .NET 9.0 offers a robust and modern development platform.

References

A Journey of Code Transformation: From Custom Validators to .NET Core Data Annotations

Introduction

Recently, I embarked on an intriguing journey of code analysis for a migration project, transitioning an application from .NET to .NET Core (.NET 8). As I delved into the codebase, I discovered a labyrinth of validation logic embedded within the model classes. A custom validator had been meticulously crafted to handle these validations, but it was clear that this approach had led to a bloated and complex codebase.

As I navigated through the code, a realization dawned upon me: many of these custom validators could be elegantly replaced with .NET’s in-built Data Annotations. This revelation was a game-changer. By leveraging these powerful attributes, we could simplify the validation logic, making it more readable and maintainable.

However, not all validations were straightforward. Some were intricate and required a level of customization that the standard Data Annotations couldn’t provide. This is where Custom Data Annotations came into play. By designing custom attributes tailored to our specific needs, we could handle even the most complex validation scenarios with ease.

The process of redesigning the application was both challenging and rewarding. As we refactored the code, we witnessed a significant reduction in the codebase. The validations became highly configurable, testable, and maintainable. The transformation was remarkable.

To illustrate the impact of this transformation, I have highlighted some of the key Data Annotations that played a pivotal role in our success. Additionally, I have showcased a few of the new annotations introduced in .NET 8 and .NET 9, which further enhanced our validation capabilities.

This journey not only improved the application’s architecture but also reinforced the importance of leveraging modern frameworks and tools to achieve cleaner, more efficient code. It was a testament to the power of .NET Core and the elegance of Data Annotations in creating robust and maintainable applications.

Intro to Data Annotations

Data Annotations in C# are a powerful way to add metadata to your classes and properties, enabling validation, formatting, and database schema generation. In this blog, we’ll explore various Data Annotations, including those newly introduced in .NET 8 and .NET 9, with real-world implementation scenarios and sample code.

Data Annotations are attributes that provide a declarative way to enforce validation rules, format data, and define database schema details. They are commonly used in ASP.NET Core MVC and Entity Framework Core.

Commonly Used Data Annotations

Required

The Required attribute ensures that a property is not null or empty.

Real-World Scenario: In a user registration form, the email field must be filled out to create an account.

Sample Code:

StringLength

The StringLength attribute specifies the minimum and maximum length of a string property.

Real-World Scenario: A product name should be between 5 and 100 characters long.

Sample Code:

public class Product
{
    [StringLength(100, MinimumLength = 5, ErrorMessage = "Product name must be between 5 and 100 characters.")]
    public string Name { get; set; }
}

Range

The Range attribute defines the minimum and maximum value for a numeric property.

Real-World Scenario: An employee’s age should be between 18 and 65.

Sample Code:

public class Employee
{
    [Range(18, 65, ErrorMessage = "Age must be between 18 and 65.")]
    public int Age { get; set; }
}

EmailAddress

The EmailAddress attribute validates that a property contains a valid email address.

Real-World Scenario: Ensuring that the contact email provided by a customer is valid.

Sample Code:

public class Contact
{
    [EmailAddress(ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }
}

Compare

The Compare attribute compares two properties to ensure they match.

Real-World Scenario: Confirming that the password and confirm password fields match during user registration.

Sample Code:

public class UserRegistration

{
    [Required]
    public string Password { get; set; }

    [Compare("Password", ErrorMessage = "Passwords do not match.")]
    public string ConfirmPassword { get; set; }
}

RegularExpression

The RegularExpression attribute validates that a property matches a specified regular expression pattern.

Real-World Scenario: Validating that a username contains only alphanumeric characters.

Sample Code:

public class User
{
    [RegularExpression(@"^[a-zA-Z0-9]*$", ErrorMessage = "Username can only contain alphanumeric characters.")]
    public string Username { get; set; }
}

MaxLength

The MaxLength attribute specifies the maximum length of a string or array property.

Real-World Scenario: Limiting the length of a product description to 500 characters.

Sample Code:

public class Product
{
    [MaxLength(500, ErrorMessage = "Description cannot exceed 500 characters.")]
    public string Description { get; set; }
}

MinLength

The MinLength attribute specifies the minimum length of a string or array property.

Real-World Scenario: Ensuring that a password is at least 8 characters long.

Sample Code:

public class User
{
    [MinLength(8, ErrorMessage = "Password must be at least 8 characters long.")]
    public string Password { get; set; }
}

CreditCard

The CreditCard attribute validates that a property contains a valid credit card number.

Real-World Scenario: Validating the credit card number provided during an online purchase.

Sample Code:

public class Payment

{

    [CreditCard(ErrorMessage = "Invalid credit card number.")]

    public string CardNumber { get; set; }

}

Url

The Url attribute validates that a property contains a valid URL.

Real-World Scenario: Ensuring that the website URL provided by a business is valid.

Sample Code:

public class Business
{
    [Url(ErrorMessage = "Invalid URL.")]
    public string Website { get; set; }
}

Phone

The Phone attribute validates that a property contains a valid phone number.

Real-World Scenario: Validating the phone number provided during user registration.

Sample Code:

public class User
{

    [Phone(ErrorMessage = "Invalid phone number.")]
    public string Phone { get; set; }

}

Custom Validation

The CustomValidation attribute allows for custom validation logic.

Real-World Scenario: Validating that a user’s age is at least 18 years old using a custom validation method.

Sample Code:

public class User
{

    [CustomValidation(typeof(UserValidator), "ValidateAge")]
    public int Age { get; set; }

}

public static class UserValidator
{
    public static ValidationResult ValidateAge(int age, ValidationContext context)
    {
        if (age < 18)
        {
            return new ValidationResult("User must be at least 18 years old.");
        }

        return ValidationResult.Success;
    }
}

New Data Annotations in .NET 8 and .NET 9

PhoneNumber (Introduced in .NET 8)

The PhoneNumber attribute validates that a property contains a valid phone number.

Real-World Scenario: Validating the phone number provided during user registration.

Sample Code:

public class User
{

    [PhoneNumber(ErrorMessage = "Invalid phone number.")]
    public string Phone { get; set; }

}

Url (Introduced in .NET 9)

The Url attribute validates that a property contains a valid URL.

Real-World Scenario: Ensuring that the website URL provided by a business is valid.

Sample Code:

public class Business
{

    [Url(ErrorMessage = "Invalid URL.")]
    public string Website { get; set; }

}

CreditCard (Introduced in .NET 9)

The CreditCard attribute validates that a property contains a valid credit card number.

Real-World Scenario: Validating the credit card number provided during an online purchase.

Sample Code:

public class Payment
{

    [CreditCard(ErrorMessage = "Invalid credit card number.")]
    public string CardNumber { get; set; }

}

Real-World Implementation Scenarios

User Registration Form

In a user registration form, it’s crucial to validate the user’s input to ensure data integrity and security. Using Data Annotations, we can enforce rules such as required fields, valid email addresses, and phone numbers.

Product Management System

In a product management system, we need to ensure that product names and descriptions meet specific length requirements. Data Annotations help us enforce these rules declaratively.

Employee Management System

In an employee management system, we need to validate employee details such as age and email address. Data Annotations provide a simple way to enforce these validation rules.

Sample Code

Here’s a complete example of a user registration form using various Data Annotations:

public class UserRegistration
{

    [Required(ErrorMessage = "Username is required.")]
    public string Username { get; set; }

    [Required(ErrorMessage = "Email is required.")]
    [EmailAddress(ErrorMessage = "Invalid email address.")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Password is required.")]
    [StringLength(100, MinimumLength = 6, ErrorMessage = "Password must be at least 6 characters long.")]
    public string Password { get; set; }

    [Phone(ErrorMessage = "Invalid phone number.")]
    public string Phone { get; set; }

}

Conclusion

Data Annotations in C# provide a powerful and declarative way to enforce validation rules, format data, and define database schema details. With the introduction of new annotations in .NET 8 and .NET 9, developers have even more tools at their disposal to ensure data integrity and improve user experience.

References