How to Trim the string in Model in Aspnet core?
How to Trim the string in Model in Aspnet core?
Why trimming the text is important? Simply, because we don’t need any white space in a string.
When you are doing any web project and implementing Rest API Service, we need to create a lot of forms, trimming every string value that the user supplied is time-consuming. So Here we have an easier and effective solution for the problem.
First, we need the IModelBinder and IModelBinderProvider. Model Binder is now at a single place on infrastructure level which will be free from any manual intervention of developer. So that we can write trimming logic in a single location.
Below we have provided all the steps and code required for the solution: First, Create the TrimingService(Named “BarbarService” here) Folder on Project Create New Class in TrimmingService Called CustomeModelBinder and Replace the Code.
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
namespace Trimming.BarbarService
{
public class CustomeModelBinder : IModelBinder
{
private readonly IModelBinder _objIModelBinder;
public CustomeModelBinder(IModelBinder objIModelBinder)
{
_objIModelBinder = objIModelBinder ?? throw new
ArgumentNullException(nameof(objIModelBinder));
}
public Task BindModelAsync(ModelBindingContext objModelBindingContext)
{
if (objModelBindingContext == null)
{
throw new ArgumentNullException(nameof(objModelBindingContext));
}
var valueProviderResult =
objModelBindingContext.ValueProvider.GetValue(objModelBindingContext.ModelName);
if (valueProviderResult != null && valueProviderResult.FirstValue is string str &&
!string.IsNullOrEmpty(str))
{
objModelBindingContext.Result = ModelBindingResult.Success(str.Trim());
return Task.CompletedTask;
}
return _objIModelBinder.BindModelAsync(objModelBindingContext);
}
}
}
CustomeModelBinder(Above code) will try to trim the string value and if doesn’t succeed, it will pass the default model binder. After that, Create a new class again in TrimmingService CustomeTrimmingModelBinderProvider for Provider for Model Binder which is required. To make sure its request is not for data type and complex type help filter and execute it.
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using System;
namespace Trimming.BarbarService
{
public class CustomeTrimmingModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext objModelBinderProviderContext)
{
if (objModelBinderProviderContext == null)
{
throw new ArgumentNullException(nameof(objModelBinderProviderContext));
}
if (!objModelBinderProviderContext.Metadata.IsComplexType &&
objModelBinderProviderContext.Metadata.ModelType == typeof(string))
{
return new CustomeModelBinder(new
SimpleTypeModelBinder(objModelBinderProviderContext.Metadata.ModelType));
}
return null;
}
}
}
Create a new class again in TrimmingService StringTrimmingHelper which helps to find the Index of SimpleTypeModelBinder and replaces it with CustomeTrimmingModelBinderProvider. If it doesn’t succeed it returns the default model binder.
All the above code is for trimming the string value. But it cannot trim the string value which came from the web API request.
To trim the string value from web API we need to Override the Function of JsonConverter
using Newtonsoft.Json;
using System;
namespace Trimming.BarbarService
{
public class ForWebApiTrimmingConverter : JsonConverter
{
public override bool CanConvert(Type objType)
{
return objType == typeof(string);
}
public override object ReadJson(JsonReader objJsonReader, Type objType, object obj,
JsonSerializer objJsonSerializer)
{
if (objJsonReader.TokenType == JsonToken.String)
{
if (objJsonReader.Value != null)
{
return (objJsonReader.Value as string).Trim();
}
}
return objJsonReader.Value;
}
public override void WriteJson(JsonWriter objJsonWriter, object obj, JsonSerializer
objJsonSerializer)
{
string str = (string)obj;
if (str == null)
{
objJsonWriter.WriteNull();
}
else
{
objJsonWriter.WriteValue(str.Trim());
}
}
}
}
The final step we need to add a line of code inside ConfigureServices in Startup.
services.AddMvc(option => option.StringTrimmingProvider())
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
.AddJsonOptions(a => a.SerializerSettings.Converters.Add(new
ForWebApiTrimmingConverter()));
Finally, this is how we trim white space from the model.
If you have any queries comment down below. Hope this article will be useful for anyone who is facing this problem.
Also, read
CRUD Operation in ASP.NET Core MVC with ADO.NET?
NET 5: One Framework, All Platforms and Open Source
Crop and upload image in ASPNET core using Jcrop