How to trim spaces of model in ASP.NET MVC Web API

99封情书 提交于 2019-11-30 20:07:06

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

    }
}

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