ASP.NETCore-ModelBinder-Collection-陷入无限循环
创始人
2024-09-17 08:00:22
0

该问题是由于在 ASP.NET Core 中的 ModelBinder 处理集合类型时遇到一个“循环引用”的情况导致的。因此,解决方法就是在 ModelBinder 中识别循环引用并将其跳过。以下是一个示例代码:

public class CustomModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (values.Length == 0)
        {
            bindingContext.Result = ModelBindingResult.Success(default(T));
            return Task.CompletedTask;
        }

        // Check if the type of the collection implements ICollection
        if (!typeof(ICollection).IsAssignableFrom(typeof(T)))
        {
            throw new InvalidOperationException($"The type {typeof(T)} must implement ICollection");
        }

        // Get T's type parameter and create a new instance of it
        var type = typeof(T).GetGenericArguments()[0];
        var collection = Activator.CreateInstance(typeof(T)) as ICollection;

        // Add an element to the collection for each value
        foreach (var value in values)
        {
            // Check if this value was already processed
            if (bindingContext.ModelState.TryGetValue(bindingContext.ModelName, out ModelStateEntry state) &&
                state.AttemptedValue == value)
            {
                continue;
            }

            // Parse the value
            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
            var element = (T)bindingContext.ValueProviderResultFrom(value, type).Model;
            collection.Add(element);
        }

        // Set the result
        bindingContext.Result = ModelBindingResult.Success(collection);
        return Task.CompletedTask;
    }
}

在以上代码中,我们为 ModelBinder 添加了一个泛型类型 T,它应该是 ICollection 的实现类型。我们用 Activator.CreateInstance 获取泛型类型参数,并创建一个新的集合。然后,我们通过遍历值来添加集合的元素。在添加元素之前,我们使用 ModelState 来检查该值是否已被处理,例如在一个循环引用的情况下。最后,我们将集合传递给 ModelBindingResult,并返回 Task.CompletedTask 来完成任务。

相关内容

热门资讯

记者揭秘!智星菠萝辅助(透视辅... 记者揭秘!智星菠萝辅助(透视辅助)拱趴大菠萝辅助神器,扑克教程(有挂细节);模式供您选择,了解更新找...
一分钟揭秘!约局吧能能开挂(透... 一分钟揭秘!约局吧能能开挂(透视辅助)hhpoker辅助靠谱,2024新版教程(有挂教学);约局吧能...
透视辅助!wepoker模拟器... 透视辅助!wepoker模拟器哪个好用(脚本)hhpoker辅助挂是真的,科技教程(有挂技巧);囊括...
透视代打!hhpkoer辅助器... 透视代打!hhpkoer辅助器视频(辅助挂)pokemmo脚本辅助,2024新版教程(有挂教程);风...
透视了解!约局吧德州真的有透视... 透视了解!约局吧德州真的有透视挂(透视脚本)德州局HHpoker透视脚本,必胜教程(有挂分析);亲,...
六分钟了解!wepoker挂底... 六分钟了解!wepoker挂底牌(透视)德普之星开辅助,详细教程(有挂解密);德普之星开辅助是一种具...
9分钟了解!wpk私人辅助(透... 9分钟了解!wpk私人辅助(透视)hhpoker德州透视,插件教程(有挂教学);风靡全球的特色经典游...
推荐一款!wepoker究竟有... 推荐一款!wepoker究竟有透视(脚本)哈糖大菠萝开挂,介绍教程(有挂技术);囊括全国各种wepo...
每日必备!wepoker有人用... 每日必备!wepoker有人用过(脚本)wpk有那种辅助,线上教程(有挂规律);wepoker有人用...
玩家必备教程!wejoker私... 玩家必备教程!wejoker私人辅助软件(脚本)哈糖大菠萝可以开挂,可靠技巧(有挂神器)申哈糖大菠萝...