我正在尝试在.net core 2.1中实现字符串修剪模型绑定程序。我要做的是创建了一个自定义模型绑定程序,为此创建了一个提供程序并将其注册在启动类中。
我的期望是,如果任何模型具有字符串属性,它将修剪值并在模型活页夹中设置。我仅针对字符串,因此我在提供程序中进行了检查,如果模型类型为字符串,则仅返回绑定程序。
但是,模型绑定程序BindModelAsync方法从未得到调用。
我错过了一些重要的代码吗?任何帮助将不胜感激。
TrimmingModelBinder
public class TrimmingModelBinder : IModelBinder
{
private readonly IModelBinder FallbackBinder;
/// <summary>
///
/// </summary>
/// <param name="fallbackBinder"></param>
public TrimmingModelBinder(IModelBinder fallbackBinder)
{
FallbackBinder = fallbackBinder ?? throw new ArgumentNullException(nameof(fallbackBinder));
}
/// <summary>
///
/// </summary>
/// <param name="bindingContext"></param>
/// <returns></returns>
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult != null &&
valueProviderResult.FirstValue is string str &&
!string.IsNullOrEmpty(str))
{
bindingContext.Result = ModelBindingResult.Success(str.Trim());
return Task.CompletedTask;
}
return FallbackBinder.BindModelAsync(bindingContext);
}
}
TrimmingModelBinderProvider
public class TrimmingModelBinderProvider : IModelBinderProvider
{
/// <summary>
///
/// </summary>
/// <param name="context"> context </param>
/// <returns></returns>
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (!context.Metadata.IsComplexType && context.Metadata.ModelType == typeof(string))
{
var loggerFactory = context.Services.GetRequiredService<ILoggerFactory>();
return new TrimmingModelBinder(new SimpleTypeModelBinder(context.Metadata.ModelType, loggerFactory));
}
return null;
}
}
Startup.cs
services
.AddMvcCore()
.AddMvcOptions(options =>
{
options.Filters.Add<ServiceClientExceptionFilter>();
var simpleTypeModelBinderProvider = options.ModelBinderProviders.First(x => x.GetType() == typeof(SimpleTypeModelBinderProvider));
var index = options.ModelBinderProviders.IndexOf(simpleTypeModelBinderProvider);
options.ModelBinderProviders.Insert(0, new TrimmingModelBinderProvider());
})