I'm using ASP.NET MVC and I'd like all user entered string fields to be trimmed before they're inserted into the database. And since I have many data entry forms, I'm looking for an elegant way to trim all strings instead of explicitly trimming every user supplied string value. I'm interested to know how and when people are trimming strings.
I thought about perhaps creating a custom model binder and trimming any string values there...that way, all my trimming logic is contained in one place. Is this a good approach? Are there any code samples that do this?
There have been a lot of posts suggesting an attribute approach. Here is a package that already has a trim attribute and many others: Dado.ComponentModel.Mutations or NuGet
After the call to Mutate(), user.UserName will be mutated to
m@x_speed.01!
.This example will trim whitespace and case the string to lowercase. It doesn't introduce validation, but the
System.ComponentModel.Annotations
can be used alongsideDado.ComponentModel.Mutations
.Extra info for anyone searching how to do this in ASP.NET Core 1.0. Logic has changed quite a lot.
I wrote a blog post about how to do it, it explains things in bit more detailed
So ASP.NET Core 1.0 solution:
Model binder to do the actual trimming
Also you need Model Binder Provider in the latest version, this tells that should this binder be used for this model
Then it has to be registered in Startup.cs
Late to the party, but the following is a summary of adjustments required for MVC 5.2.3 if you are to handle the
skipValidation
requirement of the build-in value providers.Global.asax
How about this code?
Set global.asax Application_Start event.
I disagree with the solution. You should override GetPropertyValue because the data for SetProperty could also be filled by the ModelState. To catch the raw data from the input elements write this:
Filter by propertyDescriptor PropertyType if you are really only interested in string values but it should not matter because everything what comes in is basically a string.
In ASP.Net Core 2 this worked for me. I'm using the
[FromBody]
attribute in my controllers and JSON input. To override the string handling in the JSON deserialization I registered my own JsonConverter:And this is the converter: