8 quick tips to improve your .NET API
Tags: dotnet, api
Published: 2022-04-08 20:01:28

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.

![](https://cdn-images-1.medium.com/max/2734/1*Xm4KJ5RrCPmXqHa8AYtIMQ.png)

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](https://github.com/dotnet/aspnet-api-versioning/wiki/API-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.

![](https://cdn-images-1.medium.com/max/2000/1*k85dzuMMXIXrPa8pSZqdgg.png)

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

![](https://cdn-images-1.medium.com/max/3168/1*ZwL76tVXXJsiTq5mXcDTCQ.png)

## 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.
{% gist https://gist.github.com/LucasDiogo96/02804043621c38a1511dc9075dbb86fa.js %}
And finally, use it.

    app.UseMiddleware<ExceptionMiddleware>();

You can check out more about how middleware works in .NET here: [ASP.NET Core Middleware](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0)

## 3. Enable JWT in Swagger

When our application uses bearer token authorization, to be able to test it in the swagger, it is necessary to perform the configuration below.
{% gist https://gist.github.com/LucasDiogo96/9d718d3a68e491e6f22e4f7804ab663f.js %}
After that, it will be possible to insert a JWT token generated for authorization in the swagger.

![](https://cdn-images-1.medium.com/max/2608/1*ACuJQld7Nb3-0bGK9vvGeg.png)

## 4. Access HTTP information behind a proxy.

When HTTPS requests are proxied over HTTP, the original scheme (HTTPS) is lost and must be forwarded in a header. Because an app receives a request from the proxy and not its true source on the Internet or corporate network, the originating client IP address must also be forwarded in a header.

This happens even in environments like, for example, when we are trying to capture the IP address through HttpContext.Connection.RemoteIpAddress in a docker container application.

For more information, you can access the link: [Configure ASP.NET Core to work with proxy servers and load balancers](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-6.0)

To solve it, we can use ForwardedHeaders middleware.

![](https://cdn-images-1.medium.com/max/3054/1*eROBWb73JxCezcCBDt8hHA.png)

And then use it.

    app.UseForwardedHeaders();

After that, instead of getting the proxy’s IP, it will have the X-Forwarded-For header when the request is forwarded. With these settings, the application will replace by the IP forwarding in the header.

## 5. IHttpContextAccessor instead of HTTP context

The IHttpContextAccessor is an interface to access HTTP context in .NET, and because it uses dependency injection, it is extremely useful when we need some information in service layers.

There are some good performance practices in its use. You can see it on the official Microsoft documentation: [ASP.NET Core Performance Best Practices](https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?view=aspnetcore-6.0).

First, we need to inject it.

    services.TryAddSingleton<IHttpContextAccessor,HttpContextAccessor();

![](https://cdn-images-1.medium.com/max/2668/1*CVGHNNi7lhKno1HnUY01Cw.png)

Check an example, accessing HTTP context by IHttpContextAccessor.

![](https://cdn-images-1.medium.com/max/2962/1*kK8XrMjlRhCpoIo3TUXrCw.png)

## 6. Problem Details

An RFC called Problem Details (RFC7807) [Problem Details (RFC7807)](https://datatracker.ietf.org/doc/html/rfc7807) standardizes how an error in an API should be responded to for the client. If you use [Fluent validation](https://fluentvalidation.net/), you may have noticed that the response is within this pattern.

![Response generates by fluent validation.](https://cdn-images-1.medium.com/max/2000/1*mU50ji9zEgpOZ9MHG83Urg.png)

However, there is a class that also implements this pattern, you can find the documentation here: [ProblemDetails Class](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-6.0).

As good implementation practices, it is always important to follow the patterns of some RFCs, it provides a better design.

## 7. HTTP Logging

HTTP Logging is a middleware that logs information about HTTP requests and responses. This middleware is extremely useful for visibility using logs, but it’s extremely important to keep two things in mind.

Evaluate its use for sensitive data and that this middleware can reduce application performance, especially when logging the request and response bodies, so it is important to be aware of its configuration.

You can find more about it in the documentation: [HTTP Logging in ASP.NET Core](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-logging/?view=aspnetcore-6.0)

    app.UseHttpLogging();

![(via Microsoft)](https://cdn-images-1.medium.com/max/2408/0*xwEjDep5pVDcM70Z)

## 8. Health checks

Health checks are exposed by an app as HTTP endpoints and are typically used with an external monitoring service or container orchestrator to check the status of an app. Before adding health checks to an app, decide on which monitoring system to use. The monitoring system dictates what types of health checks to create and how to configure their endpoints.

You can add the following code to the pipeline:

    builder.Services.AddHealthChecks();

Here is an example implementation in the official Microsoft documentation:

![(via Microsoft)](https://cdn-images-1.medium.com/max/2000/1*crM32CvmwUOkJM08USo4Nw.png)

In addition to exporting a health check, you can also use a UI to monitor all of your endpoints and even database connections.

![via Github(Xabaril)](https://cdn-images-1.medium.com/max/2064/1*TFSLLACeyoKGalQtAWL95A.png)

The following example demonstrates the layout of the health checker UI:

![via Github(Xabaril)](https://cdn-images-1.medium.com/max/3200/0*lXUYt5Htm6WDwTrF.png)

Above are listed some main components and patterns that I use in my day-to-day when building APIs. NET.

Hope you like it, see you in the next article.

![That’s all folks!](https://cdn-images-1.medium.com/max/2000/0*P-ivLQTgc53F2sEZ.gif)

## **References:**

**Dotnet API Versioning: [**https://github.com/dotnet/aspnet-api-versioning/wiki/API-Documentation](https://github.com/dotnet/aspnet-api-versioning/wiki/API-Documentation)

**Configure ASP.NET Core to work with proxy servers and load balancers:** [https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-6.0](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-6.0)

**Access HttpContext in ASP.NET Core:** [https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-6.0)

**Problem Details for HTTP APIs:** [https://datatracker.ietf.org/doc/html/rfc7807](https://datatracker.ietf.org/doc/html/rfc7807)

**HTTP Logging in ASP.NET Core:** [https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-logging/?view=aspnetcore-6.0](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-logging/?view=aspnetcore-6.0)

**Health checks in ASP.NET Core:** [https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-6.0](https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-6.0)

**ProblemDetails Class:** [https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-6.0](https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-6.0)