如何调试System.Core.dll中发生的"'System.ArgumentNullException',但未在用户代码中处理"

Stp*_*111 -2 c# argumentnullexception

我是C#的新手并对此感到有些困惑,主要是因为过去几个月一切都与这个网络应用程序完美配合,而这个问题刚刚开始,似乎几个月来代码没有任何变化.我在这里阅读了几篇与此错误相关的帖子,但所有答案对我的知识水平来说都是一般性的.

抛出的错误是:

System.Core.dll中出现"System.ArgumentNullException"类型的异常,但未在用户代码中处理

附加信息:值不能为空.

代码是:

[Route("ajax/addOrUpdateSource")]
[HttpPost]
public JsonResult AddOrUpdateSource(Source source, string html)
{
    var htmlDoc = new HtmlAgilityPack.HtmlDocument();
    htmlDoc.LoadHtml(html);

    var response = new Dictionary<string, object>();
    var labels = htmlDoc.DocumentNode.SelectNodes("//label");
    List<string> categories = new List<string>();
    string[] vals = new string[] { };

     for(int n = 1; n < labels.Count(); n++)
    {
        var label = labels[n].Attributes[0].Value;

        if (label.Contains( "btn") && label.Contains("btn-primary"))
            categories.Add(labels[n].InnerText.Trim());
    }

    response.Add("source", null);

    try
    {
        string catValues = String.Join(", ", categories.ToArray());

        source.LastUpdateDateTime = DateTimeOffset.UtcNow;
        source.LastUpdateUser = User.Identity.Name;
        source.ProductCategory = catValues;

        // save the source
        var updatedSource = _taskService.AddOrUpdateSource(source);

        // prepare the response
        response["source"] = updatedSource;
    }
    catch(Exception exc)
    {
        response.Add("error", exc.Message);
    }

    return Json(response);
Run Code Online (Sandbox Code Playgroud)

请参阅下面的屏幕截图,了解Visual Studio在调试期间将错误附加到何处.(包含"n <label.Count()"的行)

我怎样才能解决这个问题?我不指望我能够弄清楚为什么一切都好,突然之间就开始了,但如果我能解决它,我就能继续前进.

在此输入图像描述

更新

编辑1 - 在下面的所有非常有用的输入之后,很明显我真正需要弄清楚的是为什么应用程序突然为标签节点报告NULL.我现在能够防止错误被抛出,但在这个幻像发生变化之前,标签节点永远不会是NULL,并且执行完成了它的设计目标.

编辑2 - 根据@mjwills的指导,这里是发送数据的函数的代码:

$scope.performSaveSource = function () {
        GlobalService.togglePleaseWait(true);

        $scope.source.SourceStatusId = $scope.source.SelectedSourceStatus.SourceStatusId;
        $scope.source.SourceStatus = $scope.source.SelectedSourceStatus.SourceStatusId;
        $scope.source.DataTypeId = $scope.source.SelectedDataType.DataTypeId;

        // pass the source and activity to be saved
        $http({
            url: "/ajax/addorupdatesource",
            method: "POST",
            data: {
                source: $scope.source,
                html: $('html').context.all["143"].innerHTML
            }
        })
        .then(function (response) {
            GlobalService.togglePleaseWait(false);

            if (response.status == 200) {
                if (response.data.error != null) {
                    alert(response.data.error);
                    return;
                }

                // update our local copies
                $scope.setSource(response.data.source);
            }
        });
    };
Run Code Online (Sandbox Code Playgroud)

Eri*_*rix 5

代码可能没有改变,但是加载的html文档可能不包含任何匹配"// label"的节点

因此标签为null,并且将调用Count on it