Trimming all posted strings to an API ASP.NET CORE 3.x

Viewed 2700

Information for this as to the many .Net versions is all over the place and I cannot find a concrete up to date example.

I am attempting to automatically trim all the “string” values I post to my API’s automatically.

Note this is ASP.NET CORE 3.x which has introduced the new namespaces “System.Text.Json” etc. Rather than the Newtonsoft ones most old examples are using.

The Core 3.x API’s do not use Model Binding but rather JsonConverter(s) that I am attempting to override, therefore model binding examples are not relevant here.

The following code does work but it means that I must put the annotation:

[JsonConverter(typeof(TrimStringConverter))]

Above each string in the API models I am posting too. How can I do this so that it just does it to anything defined as a string in all the API models globally?

// TrimStringConverter.cs

// Used https://github.com/dotnet/runtime/blob/81bf79fd9aa75305e55abe2f7e9ef3f60624a3a1/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonValueConverterString.cs
// as a template From the DotNet source.


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

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

        public override void Write(
            Utf8JsonWriter writer, 
            string? value, 
            JsonSerializerOptions options)
        {
            writer.WriteStringValue(value);
        }
    }
}
// CreateUserApiModel.cs

using System.Text.Json.Serialization;

namespace User
{
    public class CreateUserApiModel
    {
        // This one will get trimmed with annotation.
        [JsonConverter(typeof(TrimStringConverter))]
        public string FirstName { get; set; }

        // This one will not.
        public string LastName { get; set; }
    }
}
// ApiController

[HttpPost]
[Route("api/v1/user/create")]
public async Task<IActionResult> CreateUserAsync(CreateUserApiModel createUserApiModel)
{
    // createUserApiModel.FirstName << Will be trimmed.
    // createUserApiModel.LastName, << Wont be trimmed.

    return Ok("{}");
}
1 Answers

As to the comment by @pinkfloydx33 above the following seems to work correctly.

// Startup.cs

services.AddControllers()
    .AddJsonOptions(options =>
     {
         options.JsonSerializerOptions.Converters.Add(new TrimStringConverter());
     });

Also for note, anybody using the code in the original question. The Converter only trims on Read and not on write unless you add another trim(). I only required it one way.

Related