gpt4 book ai didi

asp.net - 混合自定义和默认模型绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 21:23:20 26 4
gpt4 key购买 nike

我需要运行一些代码到 进一步数据绑定(bind)默认模型绑定(bind)完成后的某个模型。我不想完全替换现有的模型绑定(bind)。

这个问题解释了这是如何在 pre-CORE ASP.NET 中完成的:
ASP.NET MVC - Mixing Custom and Default Model Binding

然而,这种方法在 ASP.NET Core 中似乎不起作用,因为没有 DefaultModelBinder 上课了。

在 ASP.NET Core 中可以使用什么替代方案?

最佳答案

您可以利用 ComplexTypeModelBinder做实际的工作,然后在完成后注入(inject)你自己的逻辑。

例如(假设您的自定义类型是 MyCustomType ):

public class MyCustomType
{
public string Foo { get; set; }
}

public class MyCustomTypeModelBinder : IModelBinder
{
private readonly IDictionary<ModelMetadata, IModelBinder> _propertyBinders;

public MyCustomTypeModelBinder(IDictionary<ModelMetadata, IModelBinder> propertyBinders)
{
this._propertyBinders = propertyBinders;
}

public async Task BindModelAsync(ModelBindingContext bindingContext)
{
var complexTypeModelBinder = new ComplexTypeModelBinder(this._propertyBinders);

// call complexTypeModelBinder
await complexTypeModelBinder.BindModelAsync(bindingContext);

var modelBound = bindingContext.Model as MyCustomType;

// do your own magic here
modelBound.Foo = "custominjected";
}
}

public class MyCustomTypeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(MyCustomType))
{
var propertyBinders = new Dictionary<ModelMetadata, IModelBinder>();

for (var i = 0; i < context.Metadata.Properties.Count; i++)
{
var property = context.Metadata.Properties[i];
propertyBinders.Add(property, context.CreateBinder(property));
}

return new MyCustomTypeModelBinder(propertyBinders);
}

return null;
}
}

然后注册它:
services.AddMvc(options =>
{
options.ModelBinderProviders.Insert(0, new MyCustomTypeModelBinderProvider());
});

关于asp.net - 混合自定义和默认模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50149845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com