Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove extra spaces in input model in dot net core?

I have found a link to remove extra spaces in the model properties which is string type How to trim spaces of model in ASP.NET MVC Web API

How to achieve the same functionality in dot net core 2.1 web api?

Or is there any build in formatters available in dotnet core for removing extra spaces in input and output model?

Thanks in advance?

like image 776
Magendran V Avatar asked Oct 21 '25 15:10

Magendran V


1 Answers

I believe the answer you linked is probably your best option. So create a converter as per the anwser.

class TrimmingConverter : JsonConverter
{
  public override bool CanConvert(Type objectType)
  {
    return objectType == typeof(string);
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    if (reader.TokenType == JsonToken.String)
      if (reader.Value != null)
        return (reader.Value as string).Trim();

    return reader.Value;
  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    var text = (string)value;
    if (text == null)
      writer.WriteNull();
    else
      writer.WriteValue(text.Trim());
  }
}

And then register it in your ConfigureServices method in your Startup class like so:

public void ConfigureServices(IServiceCollection services)
{
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddJsonOptions(a => a.SerializerSettings.Converters.Add(new TrimmingConverter()));
}
like image 196
erikbozic Avatar answered Oct 23 '25 03:10

erikbozic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!