问题描述
修剪传递给MVC Web api(具有复杂对象的post方法)的模型的所有属性的最佳方法是什么.可以简单完成的一件事就是在所有属性的getter中调用Trim函数.但是,我真的不喜欢.
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.
我想要一种简单的方法,类似于在这里为MVC提到的方法
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?
推荐答案
要在Web API中修剪所有传入的字符串值,可以定义Newtonsoft.Json.JsonConverter
:
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());
}
}
然后在Application_Start
上注册.约定在FormatterConfig
中执行此操作,但是您也可以在Global.asax.cs
的Application_Start
中执行此操作.它在FormatterConfig
中:
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());
}
}
这篇关于如何在ASP.NET MVC Web API中修剪模型空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!