7

修剪传递给 MVC Web api 的模型的所有属性的最佳方法是什么(具有复杂对象的 post 方法)。可以简单做的一件事是在所有属性的 getter 中调用 Trim 函数。但是,我真的不喜欢那样。

我想要一种简单的方法,类似于此处为 MVC 提到的ASP.NET MVC:在数据输入后修剪字符串的最佳方法。我应该创建自定义模型绑定器吗?

4

2 回答 2

15

要在 Web API 中修剪所有传入的字符串值,您可以定义一个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());
    }
}

然后在 上注册Application_Start。在 中执行此操作的约定FormatterConfig,但您也可以在Application_Startof 中执行此操作Global.asax.cs。这是在FormatterConfig

public static class FormatterConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Formatters.JsonFormatter.SerializerSettings.Converters
            .Add(new TrimmingConverter());

    }
}
于 2015-12-15T22:29:46.257 回答
1

我无法找到任何与 XML 等效的东西,以下内容也是如此

    /// <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;
        }
    }

然后将默认的 XmlMediaTypeFormatter 更改为

    config.Formatters.Clear();

    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.Formatters.Add(new CustomXmlMediaTypeFormatter());
于 2018-10-10T09:29:42.453 回答