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

孤街醉人 提交于 2019-12-10 18:28:38

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/51569353/how-to-remove-extra-spaces-in-input-model-in-dot-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!