Home > Software engineering >  How to make .NET 6 API automatically convert an empty string from the request body into null?
How to make .NET 6 API automatically convert an empty string from the request body into null?

Time:08-02

I have a .NET 6 API with the following DTO and controller:

public class AnimalDTO
{
    // ...
    public string? Owner { get; set; }
}
[HttpGet]
public async Task CreateAnimal([FromBody] AnimalDTO animal)
{
    // ...
} 

Whenever someone makes a request with Owner as an empty string, I would like for it to be converted to null automatically. I would also like this to be, automatically, the case for any other string? body parameter.

Is there any way to do this in Asp.Net 6?

CodePudding user response:

You can use a custom JsonConverter to convert empty strings:

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

namespace MyApp.Converters
{
    public class EmptyStringConverter : JsonConverter<string>
    {
        public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return reader.GetString();
        }

        public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
        {
            if(string.IsNullOrEmpty(value))
            {
                writer.WriteNullValue();
                return;
            }

            writer.WriteStringValue(value);
        }
    }
}

To use this converter on a single property, you can annotate it like so:

[JsonConverter(typeof(EmptyStringConverter))]
public string Owner { get; set; }

To use the converter globally on all properties of type string, you can register the converter when adding your controllers in your Program.cs like so:

builder.Services.AddControllers().AddJsonOptions(jsonOptions =>
{
    jsonOptions.JsonSerializerOptions.Converters.Add(new EmptyStringConverter());
});

If you are using Json.NET/Newtonsoft.json, you can adapt my code to work with their specification for custom converters.

CodePudding user response:

Are you sure thats what you want? You could just use string.IsNullOrEmpty() in your validation then it wouldn't matter if its null or empty string.


Otherwise you could try to set the default value to null but that doesn't prevent an empty string value being sent in from the client. Also Note that the string type is a reference type and always nullable, you don't need to add the ?.

public class AnimalDTO
{
    // ...
    public string Owner { get; set; } = null;
}

If you must set empty strings to null then unfortunately there is no "Automatic" way that I know of, however you can set them to null with reflection, this is my cleanest attempt.

private void SetEmptyStringsToNull(object obj)
{
    foreach (PropertyInfo info in obj.GetType().GetProperties())
    {
        if (info.PropertyType == typeof(string) && info.GetValue(obj) as string == string.Empty)
        {
            info.SetValue(obj, null, null);
        }
    }
}

[HttpGet]
public async Task CreateAnimal([FromBody] AnimalDTO animal)
{
    SetEmptyStringsToNull(animal);
    // ...
}
  • Related