简体   繁体   中英

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?

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()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM