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

What is the best way to trim all the model properties passed to the MVI web api (post method with a complex object). You can simply make a call to the Trim function in the getter of all the properties. But I really don't like it.

I need a simple way similar to the one specified for MVC here ASP.NET MVC: the best way to trim lines after data input. Should I create a custom mediator?

+4
source share
1 answer

To trim all incoming string values โ€‹โ€‹in a web API, you can define 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 it on Application_Start . The convention for this is in FormatterConfig , but you can also do this in Application_Start 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()); } } 
+7
source

Source: https://habr.com/ru/post/1483555/


All Articles