What is the best way to trim all the properties of the model passed to the MVC web api (post method with complex object). One thing simply can be done is calling Trim function in the getter of all the properties. But, I really do not like that.
I want the simple way something like the one mentioned for the MVC here ASP.NET MVC: Best way to trim strings after data entry. Should I create a custom model binder?
To trim all incoming string values in Web API, you can define a Newtonsoft.Json.JsonConverter
:
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());
}
}
Then register this on Application_Start
. The convention to do this in FormatterConfig
, but you can also do this in Application_Start
of Global.asax.cs
. Here it is in FormatterConfig
:
public static class FormatterConfig
{
public static void Register(HttpConfiguration config)
{
config.Formatters.JsonFormatter.SerializerSettings.Converters
.Add(new TrimmingConverter());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With