如何调试 JavaScript inside ASP .Net Core 3.1 MVC 应用程序(Razor 视图 - *.cshtml)?

Howto debug JavaScript inside ASP .Net Core 3.1 MVC applications (Razor view - *.cshtml)?

我有最新的 Visual Studio 2019 16.5.4 Enterprise.

我刚刚从模板(使用默认设置)创建了一个 ASP .Net Core 3.1 MVC 应用程序。

并且我在主页的 Index.cshtml:

中添加了一些 JavaScript 代码
@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>


@section Scripts {
    <script>
        function GetJSON_Simple() {
            var resp = [];           
            return resp;
        }

        debugger;
        var simpleData = GetJSON_Simple();

    </script>
}

而且我无法调试 JavaScript 代码(GetJSON_Simple 函数体内或 var simpleData = GetJSON_Simple() 上的断点永远不会命中)。我已经尝试了 Chrome 和 MS Edge (Chromium)。

根据 this article使用 Razor (ASP.NET) 在动态文件中调试 JavaScript 部分):

Place the debugger; statement where you want to break: This causes the dynamic script to stop execution and start debugging immediately while it is being created.

P.S。我已经有 Tools->Options->Debugging->General 打开 Enable JavaScript Debugging for ASP.NET (Chrome 和 IE) 复选框,当然我正在调试中编译。

我的测试项目是attached

Howto debug JavaScript inside ASP .Net Core 3.1 MVC applications (Razor view - *.cshtml)?

其实已经是众所周知的问题了。 无法调试Net Core razor页面下的js代码,只能调试单独的js或ts文件中的代码。参见

解决方案

为了解决这个问题,我建议你可以创建一个新的名为test.js的单个js文件,然后在razor页面中引用它,然后你可以在调试它的时候进入js代码。

1) 创建一个名为 test.js 的文件并将您的 js 代码迁移到其中:

 function GetJSON_Simple() {
            var resp = [];           
            return resp;
        }

        debugger;
        var simpleData = GetJSON_Simple();

2) 更改为在您的 cshtml 文件中使用它:

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>


@section Scripts {
    <script scr="xxx/test.js">  
    </script>
}

3) 清理你的项目,然后重建你的项目并调试它,然后你会打到Js代码。