【问题标题】:Custom model binding in AspNet Core WebApi?AspNet Core WebApi 中的自定义模型绑定?
【发布时间】:2020-09-04 00:55:06
【问题描述】:

任何人都有一个使用多态模型绑定的自定义模型绑定的工作示例?我正在尝试this example(用于 Mvc 而不是 Api 项目)与 web api 项目,但它不适用于 API 项目。我认为在填充ValueProvider 方面缺少一些步骤,但我找不到与此相关的任何资源(AspNet Core 3.1)。

到目前为止我的尝试:

Dtos:

public abstract class Device
{
    public string Kind { get; set; }
}

public class Laptop : Device
{
    public string CPUIndex { get; set; }
}

public class SmartPhone : Device
{
    public string ScreenSize { get; set; }
}

自定义模型绑定器实现:

public class DeviceModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context.Metadata.ModelType != typeof(Device))
        {
            return null;
        }

        var subclasses = new[] { typeof(Laptop), typeof(SmartPhone), };

        var binders = new Dictionary<Type, (ModelMetadata, IModelBinder)>();
        foreach (var type in subclasses)
        {
            var modelMetadata = context.MetadataProvider.GetMetadataForType(type);
            binders[type] = (modelMetadata, context.CreateBinder(modelMetadata));
        }

        return new DeviceModelBinder(binders);
    }
}

public class DeviceModelBinder : IModelBinder
{
    private Dictionary<Type, (ModelMetadata, IModelBinder)> binders;

    public DeviceModelBinder(Dictionary<Type, (ModelMetadata, IModelBinder)> binders)
    {
        this.binders = binders;
    }

    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var modelKindName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, nameof(Device.Kind));
        var modelTypeValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        IModelBinder modelBinder;
        ModelMetadata modelMetadata;
        if (modelTypeValue.FirstValue == "Laptop")
        {
            (modelMetadata, modelBinder) = binders[typeof(Laptop)];
        }
        else if (modelTypeValue.FirstValue == "SmartPhone")
        {
            (modelMetadata, modelBinder) = binders[typeof(SmartPhone)];
        }
        else
        {
            bindingContext.Result = ModelBindingResult.Failed();
            return;
        }

        var newBindingContext = DefaultModelBindingContext.CreateBindingContext(
            bindingContext.ActionContext,
            bindingContext.ValueProvider,
            modelMetadata,
            bindingInfo: null,
            bindingContext.ModelName);

        await modelBinder.BindModelAsync(newBindingContext);
        bindingContext.Result = newBindingContext.Result;

        if (newBindingContext.Result.IsModelSet)
        {
            // Setting the ValidationState ensures properties on derived types are correctly 
            bindingContext.ValidationState[newBindingContext.Result] = new ValidationStateEntry
            {
                Metadata = modelMetadata,
            };
        }
    }
}

我像这样注册模型绑定器提供程序:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers(o => o.ModelBinderProviders.Insert(0, new DeviceModelBinderProvider()));
    }

然后是我的控制器:

[ApiController]
[Route("test")]
public class TestController : ControllerBase
{
    [HttpPost]
    public IActionResult Test(Device dto)
    {
        var x = dto;
        return Ok();
    }
}

我正在发布一个 json 请求正文,例如:

{
    "ScreenSize": "1",
    "Kind": "SmartPhone"
}

真的厌倦了这方面的文档,因为有太多的魔法发生了。我的后备是从请求中手动解析 HttpContent 并反序列化。但我希望使用示例中的模型绑定方法。我看到的唯一两件奇怪的事情是,bindingContext.ModelName 是空的,bindingContext.ValueProvider 只有一个包含 action 和 controller 键的路由值提供程序。所以,看起来 body 甚至没有解析到值提供者中。

【问题讨论】:

    标签: c# asp.net-core model-binding custom-model-binder


    【解决方案1】:

    格式化程序,当 JSON 数据不与模型绑定\值提供程序子系统的其余部分交互时使用。对于这种情况,您必须为您正在使用的 JSON 库编写一个转换器。

    更多信息:

    相关信息

    【讨论】:

    • 你能解释一下json格式化程序不与模型绑定的其余部分交互是什么意思吗?你的意思是json请求没有被正确解析?
    【解决方案2】:

    我已经尝试过与您发布的完全相同的代码,并且它对我有用。

    这是其价值的形象。

    这是邮递员请求的截图。

    来自邮递员的 CURL 请求。

    curl --location --request POST 'https://localhost:44332/test' \
    --header 'Content-Type: application/json' \
    --form 'ScreenSize=1' \
    --form 'Kind=SmartPhone'
    

    和startup.cs 如下图所示。

    【讨论】:

    • 您使用的是哪个版本的 dotnet core?您能否将整个项目上传到某个地方,以便我可以尝试运行它?
    • .Net Core 3.1,我认为您的请求中可能缺少 content-type 标头。
    • 检查此信息:“格式化程序,这是在 JSON 数据不与模型绑定\值提供程序子系统的其余部分交互时使用的。对于这种情况,您必须编写一个转换器对于您正在使用的 JSON 库”。来源和更多信息:[AspNetCore 3.1 Api 中的多态模型绑定](github.com/dotnet/aspnetcore/issues/21939)
    • 这就是为什么不使用表单数据时它不起作用
    • @richardsonwtr 和你的评论在这里我也了解了真正的原因,这将是有帮助的,这就是我喜欢这个社区的原因。我们帮助别人,我们从别人那里得到帮助,同时我们也获得了知识。也为你的努力 +1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 2023-03-30
    • 1970-01-01
    • 2016-09-13
    • 2018-08-22
    • 2017-02-09
    相关资源
    最近更新 更多