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

眉间皱痕 提交于 2019-11-30 03:58:16

问题


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?


回答1:


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

    }
}



回答2:


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


来源:https://stackoverflow.com/questions/16834600/how-to-trim-spaces-of-model-in-asp-net-mvc-web-api

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