Introduction

Converting a string to an enum is a common requirement when building web APIs. Enums provide a way to define a set of named constants that represent a fixed set of values. However, the data sent from the client to the web API is often in the form of a string.

In this blog post, we’ll explore the process of converting a string from the client to an enum in a web API built on the . NET platform using C#. We’ll walk through the steps needed to handle this conversion and provide some tips and best practices to make the process as smooth as possible. By the end of this post, you’ll have a clear understanding of how to handle string-to-enum conversions in your web API projects.

Background

Converting strings to enums is an important consideration for any web API built on the C#/. NET platform. In fact, this conversion may need to happen in two separate situations:

  1. when the API receives a request from a frontend client, and
  2. when the API receives a response from an external service.

Solution

Handling string-to-enum conversions in incoming requests

Configuring string-to-enum conversions for incoming requests is as simple as adjusting the options in the Program.cs file, allowing for efficient validation and mapping of incoming string data.

Implementation

Edit Program.cs

1
2
3
4
5
6
7
8
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(
new JsonStringEnumConverter());

options.JsonSerializerOptions.DefaultIgnoreCondition
= JsonIgnoreCondition.WhenWritingNull;
});

Handling string-to-enum conversions in incoming responses

String-to-enum conversions for incoming responses can be more complex than those for incoming requests. To ensure consistency and maintainability, it is recommended to use a Unit of Work when handling these conversions.

Implementation

  1. Edit Infrastructure/UnitOfWork.cs
1
2
3
4
5
6
7
8
9
10
11
public sealed class UnitOfWork:
{
public IConfiguration Configuration { get; }

public JsonSerializerOptions JsonSerializerOptions {
get;
} = new JsonSerializerOptions {
Converters = { new JsonStringEnumConverter(
JsonNamingPolicy.CamelCase) },
};
}
  1. Edit Services/CustomService/CustomService.cs
1
2
3
4
5
6
7
8
9
10
11
public class CustomService : ICustomService
{
private readonly UnitOfWork _uow;

public CustomService(UnitOfWork uow) { _uow = uow; }

public async Task<CustomResponse?> GetAsync() =>
await _uow.HttpClientFactory.CreateClient().GetFromJsonAsync(
_uow.Configuration["ExternalServiceUrl"],
_uow.JsonSerializerOptions);
}

Conclusion

Handling string-to-enum conversions is essential for reliable data management in web API development. While converting in incoming requests is straightforward, incoming responses can be more complex. Following best practices like using a Unit of Work and configuring options can ensure accurate conversions. By doing so, developers can build efficient web APIs that handle string-to-enum conversions with ease.