ASP.NET Core自定义绑定ModelName始终为空

Mic*_*hal 5 asp.net asp.net-mvc asp.net-core asp.net-core-2.1

我已经实现了自定义活页夹:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

以及相应的模型绑定器提供者:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我已将自定义活页夹提供程序添加到 ModelBinderProviders 集合中:

services.AddMvc(options => options.ModelBinderProviders.Insert(0, new CustomModelBinderProvider()));
Run Code Online (Sandbox Code Playgroud)

除了一件事之外,一切都正常。正在调用自定义绑定器,但不幸的是,bingingContext.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
Run Code Online (Sandbox Code Playgroud)

我不知道在 ModelName 和 ValueProvider 方面缺少什么。

更新: CustomModel 用于继承 ApiController 的控制器。控制器中的方法签名如下所示:

[HttpPost]
public async Task<IActionResult> UpsertModel(string Id, [FromBody] CustomModel model)
Run Code Online (Sandbox Code Playgroud)