在视图中获取 InvalidOperationException.Collection 已修改错误

getting InvalidOperationException.Collection was modified error in view

我有一个 .Net 核心 Web 应用程序。我的代码在调试模式下运行完美,在服务器上,我没有看到任何可见的错误。但是这个错误在我的记录器中重复记录。

System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
 at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
 at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Func`2 predicate, Boolean& found)
 at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
 at AspNetCore.Views_Home__ItemsList.ExecuteAsync() in [project path]\Views\Home\_ItemsList.cshtml:line 56

我不明白为什么会这样,我没有更改视图中的列表。

IndexDto

public class IndexDto
{
    public List<SliderListDto> Sliders { get; set; }
    public List<ItemDto> Featured { get; set; }
    public ResourceList<ItemDto> Items { get; set; }        
}

资源列表

public class ResourceList<T>
{
    public ResourceList() { }
    public ResourceList(List<T> items, bool hasMore = false)
    {
        Items = items;
        HasMore = hasMore;
    }
    public List<T> Items { get; set; }
    public bool HasMore { get; set; }
    public List<Link> Links { get; set; } = new List<Link>();
}

Index.cshtml

@model IndexDto
<div class="home">
    @await Html.PartialAsync("_Sliders", Model.Sliders)
    @await Html.PartialAsync("_Featured", Model.Featured)
    @await Html.PartialAsync("_ItemsList", Model.Items)
</div>

_ItemsList.cshtml

@if (Model.Items.Any())
{
    @*some html here*@
    @foreach (var item in Model.Items)
    {
        @*some html here*@
        @if (item.IsOnline)
        {
            @*some html here*@
        }
        @*some html here*@
        @if (item.OnlineUsersCount > 0)
        {
            @*some html here*@
        }           
    }
    
    @if (Model.HasMore)
    {
        var nextLink = Model.Links.First(l => l.Rel == "next"); //This is where the error happens

        if (nextLink != null)
        {
            @*some html here*@
        }
    }
    @*some html here*@
}

我唯一一次修改 Links 列表是在控制器的这个方法中:

public class HomeController : Controller
{

    public async Task<IActionResult> Index()
    {
        var model = await _queryManager.GeMainPage();
        SetResourceLinks(model);
        return View(model);
    }

    private void SetResourceLinks(IndexDto result)
    {
        if (result.Items.HasMore)
        {
            result.Items.Links.Add(new Link(
                "next",
                Url.Action(nameof(ItemsController.GetItems), "Items", new { pageNumber = 2}, Request.Scheme),
                HttpMethods.Get));
        }
    }
}

我正在这个应用上使用负载平衡。会不会跟那个有关?

更新

我在 _queryManager.GeMainPage() 方法中找到了问题的根源。

public async Task<HeyatIndexDto> GetMainPage()
{
    var model = await _redisCache.GetOrCreateAsync(CacheKeys.IndexModel, entry =>
    {
        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);
        return GetMainPageFromDatabase();
    });
    return model;
}

private async Task<IndexDto> GetMainPageFromDatabase()
{
    //....
}

我将数据作为对象存储在 Redis 中,当我检索它时,它并没有创建新对象并将链接添加到先前的数组。我更改了将数据存储为字符串然后反序列化的方法。问题已解决。

public async Task<HeyatIndexDto> GetHeyatMainPage()
{
    var serializedData = await _cache.GetOrCreateAsync(CacheKeys.HeyatIndexModel, entry =>
    {
        entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5);
        return GetHeyatMainPageFromDatabase();
    });
    var model = JsonSerializer.Deserialize<HeyatIndexDto>(serializedData);
    return model;
}

private async Task<string> GetHeyatMainPageFromDatabase()
{
    //....
}

我在项目的另一层找到了问题的根源。

在 _queryManager.GeMainPage() 方法中,我将数据作为对象存储在 Redis 中,当我检索它时,它并没有创建新对象并将链接添加到先前的数组。我更改了将数据存储为字符串然后反序列化的方法。问题已解决。

我在原来的 post 中添加了包含 GeMainPage 代码的更新。