8

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?

0

2 Answers 2

16

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

    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

How about for XML?
But it's solution without possibilities to manage which fields stay without trimming
Worth mentioning this is also applicable to asp.net core 3.x with some minor modifications.
1

I was unable to find anything equivalent for XML, so did the following

    /// <summary>
    /// overriding read xml to trim whitespace
    /// </summary>
    /// <seealso cref="System.Net.Http.Formatting.XmlMediaTypeFormatter" />
    public class CustomXmlMediaTypeFormatter : XmlMediaTypeFormatter
    {

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = base.ReadFromStreamAsync(type, readStream, content, formatterLogger);

            // the inner workings of the above don't actually do anything async
            // so not actually breaking the async by getting result here.

            var result = task.Result;
            if (result.GetType() == type)
            {
                // okay - go through each property and trim / nullify if string
                var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

                foreach (var p in properties)
                {
                    if (p.PropertyType != typeof(string))
                    {
                        continue;
                    }

                    if (!p.CanRead || !p.CanWrite)
                    {
                        continue;
                    }

                    var value = (string)p.GetValue(result, null);
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        p.SetValue(result, null);
                    }
                    else
                    {
                        p.SetValue(result, value.Trim());
                    }
                }
            }

            return task;
        }
    }

and then changed the default XmlMediaTypeFormatter to

    config.Formatters.Clear();

    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.Add(new CustomXmlMediaTypeFormatter());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.