我已经实现了自定义资料夹:
public class CustomModelBinder : IModelBinder
{
public Task BindmodelAsync(ModelBindingContext bindingContext)
{
var modelName = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.Getvalue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
var modelAsString = valueProviderResult.Firstvalue;
if (!string.IsnullOrEmpty(modelAsString))
{
// custom login here
}
return Task.CompletedTask;
}
}
和相应的模型联编程序提供者:
public class CustomModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(CustomModel))
{
return new BinderTypeModelBinder(typeof(CustomModelBinder));
}
return null;
}
}
并且我已经将自定义的绑定提供程序添加到了ModelBinderProviders集合中:
services.AddMvc(options => options.ModelBinderProviders.Insert(0,new CustomModelBinderProvider()));
除一件事外,所有事物都起作用。自定义联编程序被调用,但不幸的是bindingContext.ModelName始终为空,不知道为什么。由于ModelName为空,所以我总是得到ValueProviderResult.None作为值提供者。
var modelName = bindingContext.ModelName; //ModelName is empty here
var valueProviderResult = bindingContext.ValueProvider.Getvalue(modelName); // I will get ValueProviderResult.None on this line
我不知道我在ModelName和ValueProvider方面缺少什么。
更新: CustomModel用于继承ApiController的控制器中。控制器中的方法签名如下:
[HttpPost]
public async Task<IactionResult> UpsertModel(string Id,[FromBody] CustomModel model)