8 quick tips to improve your .NET API

Every day we need to develop new APIs, whether at work or for study purposes, and some features can help us with the use of good practices in a simple way. And through this post, I want to show you some features that I use daily.

1. API Versioning

One of the challenges for those who build APIs is changing contracts that are already in use in the production environment. Clients may not want to update their applications when the API changes, so a versioning strategy becomes crucial.

A versioning strategy allows clients to continue using the existing REST API and migrate their applications to the newer API when they are ready.

In .NET, we can versioning our APIs through the addApiVersioning extension.

This API versioning can be parameterized with some options, including the default version or even how the versioning will be done, whether by URL, header, or media type. For more details, you can access the official documentation.

After the configuration performed above, it is necessary to inform the API version through the attribute. If it has been configured by URL, it will be necessary to parameterize it.

And in the API specification, you will get the following result.

2. Global Exception Handler

Instead of creating lots of try-catch throughout the code to handle unexpected errors by our application, we can simply create a middleware that handles exceptions globally.

using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc;

namespace Sample.Identity.API.Midlewares
    public class ExceptionMiddleware    
        private readonly RequestDelegate next;