升级Bootstrap 5.3.3后运行ASP.NET MVC应用遇空引用异常求助
翻译后的错误信息
对象引用未设置为对象的实例。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详情:System.NullReferenceException: 对象引用未设置为对象的实例。
源错误:
Line 39: Line 40: @Scripts.Render("~/bundles/jquery") Line 41: @Scripts.Render("~/bundles/bootstrap") Line 42: @RenderSection("scripts", required: false) Line 43: </body>
源文件:C:\Users\uptown\Documents\Education\Personal Information\Portfolio\C#\WebApplication1\Views\Shared_Layout.cshtml 第41行
问题原因
Bootstrap 5不再依赖jQuery,且NuGet安装的Bootstrap 5文件结构与旧版本差异较大,原有的~/bundles/bootstrap捆绑配置找不到对应文件,导致Scripts.Render调用时触发空引用异常。
修复步骤
更新BundleConfig配置
打开App_Start/BundleConfig.cs,删除旧的Bootstrap脚本捆绑配置,替换为Bootstrap 5的正确路径:// 移除旧配置:bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(...)); // 添加新配置(路径以NuGet实际安装位置为准) bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/lib/bootstrap/dist/js/bootstrap.bundle.min.js" ));注:Bootstrap 5的
bootstrap.bundle.min.js已集成Popper.js,无需单独引用。验证文件路径
检查项目lib/bootstrap/dist/js目录下是否存在bootstrap.bundle.min.js,若NuGet安装路径不同,以实际路径调整。清理重建项目
依次执行:「生成」→「清理解决方案」→「生成」→「重建解决方案」,清除浏览器缓存后重新运行。备选方案:直接引用脚本
若捆绑配置仍有问题,可直接在_Layout.cshtml中替换@Scripts.Render("~/bundles/bootstrap")为:<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
内容的提问来源于stack exchange,提问作者Blake Only

