ASP.NET Core 项目疑难解答和调试Troubleshoot and debug ASP.NET Core projects

作者:Rick AndersonBy Rick Anderson

以下链接提供了故障排除指南:The following links provide troubleshooting guidance:

.NET Core SDK 警告.NET Core SDK warnings

同时安装了 .NET Core SDK 的32位和64位版本Both the 32-bit and 64-bit versions of the .NET Core SDK are installed

新项目对话框为 ASP.NET Core,你可能会看到以下警告:In the New Project dialog for ASP.NET Core, you may see the following warning:

同时安装了 .NET Core SDK 的32位和64位版本。Both 32-bit and 64-bit versions of the .NET Core SDK are installed. 仅显示64位版本中安装了 "C:\Program Files\dotnet\sdk\" 的模板。Only templates from the 64-bit versions installed at 'C:\Program Files\dotnet\sdk\' are displayed.

时,此警告会出现 (x86) 32 位和 64 位 (x64) 版本的.NET Core SDK安装。This warning appears when both 32-bit (x86) and 64-bit (x64) versions of the .NET Core SDK are installed. 这两个版本可能安装的常见原因包括:Common reasons both versions may be installed include:

  • 你最初下载.NET Core SDK 安装程序使用 32 位计算机,但然后复制它跨并安装在 64 位计算机上。You originally downloaded the .NET Core SDK installer using a 32-bit machine but then copied it across and installed it on a 64-bit machine.
  • 由另一个应用程序安装了 32 位.NET Core SDK。The 32-bit .NET Core SDK was installed by another application.
  • 下载并安装了错误的版本。The wrong version was downloaded and installed.

卸载 32 位.NET Core SDK,以防止出现此警告。Uninstall the 32-bit .NET Core SDK to prevent this warning. "控制面板" > " 程序和功能" 中卸载 > 卸载或更改程序Uninstall from Control Panel > Programs and Features > Uninstall or change a program. 如果了解警告出现的原因及其含义,可以忽略此警告。If you understand why the warning occurs and its implications, you can ignore the warning.

.NET Core SDK 的安装在多个位置The .NET Core SDK is installed in multiple locations

新项目对话框为 ASP.NET Core,你可能会看到以下警告:In the New Project dialog for ASP.NET Core, you may see the following warning:

.NET Core SDK 安装在多个位置中。The .NET Core SDK is installed in multiple locations. 仅显示在 "C:\Program Files\dotnet\sdk\" 上安装的 Sdk 中的模板。Only templates from the SDKs installed at 'C:\Program Files\dotnet\sdk\' are displayed.

外部的一个目录中有至少一个安装的.NET Core SDK 时,将显示此消息c:\Program Files\dotnet\sdk\You see this message when you have at least one installation of the .NET Core SDK in a directory outside of C:\Program Files\dotnet\sdk\. 这通常发生在使用复制/粘贴,而不 MSI 安装程序的计算机上部署了.NET Core SDK 时。Usually this happens when the .NET Core SDK has been deployed on a machine using copy/paste instead of the MSI installer.

卸载所有32位 .NET Core Sdk 和运行时,以防出现此警告。Uninstall all 32-bit .NET Core SDKs and runtimes to prevent this warning. "控制面板" > " 程序和功能" 中卸载 > 卸载或更改程序Uninstall from Control Panel > Programs and Features > Uninstall or change a program. 如果了解警告出现的原因及其含义,可以忽略此警告。If you understand why the warning occurs and its implications, you can ignore the warning.

检测到没有.NET Core SdkNo .NET Core SDKs were detected

  • 在 ASP.NET Core 的 Visual Studio "新建项目" 对话框中,你可能会看到以下警告:In the Visual Studio New Project dialog for ASP.NET Core, you may see the following warning:

    未检测到任何 .NET Core Sdk,请确保它们包含在环境变量 PATH中。No .NET Core SDKs were detected, ensure they are included in the environment variable PATH.

  • 执行 dotnet 命令时,警告显示为:When executing a dotnet command, the warning appears as:

    找不到任何已安装的 dotnet Sdk。It was not possible to find any installed dotnet SDKs.

如果环境变量 PATH 不指向计算机上的任何 .NET Core Sdk,则会出现这些警告。These warnings appear when the environment variable PATH doesn't point to any .NET Core SDKs on the machine. ИфЅвѕцґЛОКМв,ЗлЦґРРТФПВІЩЧч:To resolve this problem:

  • 安装 .NET Core SDK。Install the .NET Core SDK. .Net 下载获取最新的安装程序。Obtain the latest installer from .NET Downloads.
  • 验证 PATH 环境变量是否指向安装 SDK 的位置(对于64位/x64,则为C:\Program Files\dotnet\,对于32位/x86 为 C:\Program Files (x86)\dotnet\)。Verify that the PATH environment variable points to the location where the SDK is installed (C:\Program Files\dotnet\ for 64-bit/x64 or C:\Program Files (x86)\dotnet\ for 32-bit/x86). SDK 安装程序通常会设置 PATHThe SDK installer normally sets the PATH. 始终在同一台计算机上安装相同的位数 Sdk 和运行时。Always install the same bitness SDKs and runtimes on the same machine.

安装 .NET Core 托管捆绑包后缺少 SDKMissing SDK after installing the .NET Core Hosting Bundle

安装 .net Core 托管捆绑会在安装 .net core 运行时以指向 .net core 的32位(x86)版本(C:\Program Files (x86)\dotnet\)时修改 PATHInstalling the .NET Core Hosting Bundle modifies the PATH when it installs the .NET Core runtime to point to the 32-bit (x86) version of .NET Core (C:\Program Files (x86)\dotnet\). 当使用32位(x86) .NET Core dotnet 命令时,这可能会导致缺少 Sdk (未检测到 .Net Core sdk)。This can result in missing SDKs when the 32-bit (x86) .NET Core dotnet command is used (No .NET Core SDKs were detected). 若要解决此问题,请将 C:\Program Files\dotnet\ 移到 PATH之前 C:\Program Files (x86)\dotnet\ 的位置。To resolve this problem, move C:\Program Files\dotnet\ to a position before C:\Program Files (x86)\dotnet\ on the PATH.

从应用中获取数据Obtain data from an app

如果某个应用能够响应请求,则可以使用中间件从应用获取以下数据:If an app is capable of responding to requests, you can obtain the following data from the app using middleware:

  • Request – 方法,方案,主机,pathbase,路径,查询字符串,标头Request – Method, scheme, host, pathbase, path, query string, headers
  • 连接 – 远程 IP 地址,远程端口,本地 IP 地址,本地端口,客户端证书Connection – Remote IP address, remote port, local IP address, local port, client certificate
  • 标识 – 名称,显示名称Identity – Name, display name
  • 配置设置Configuration settings
  • 环境变量Environment variables

将以下中间件代码置于 Startup.Configure 方法的请求处理管道的开头。Place the following middleware code at the beginning of the Startup.Configure method's request processing pipeline. 在运行中间件之前会检查环境,以确保仅在开发环境中执行代码。The environment is checked before the middleware is run to ensure that the code is only executed in the Development environment.

若要获取环境,请使用以下方法之一:To obtain the environment, use either of the following approaches:

  • IHostingEnvironment 插入到 Startup.Configure 方法中,并检查带有本地变量的环境。Inject the IHostingEnvironment into the Startup.Configure method and check the environment with the local variable. 下面的示例代码演示了这种方法。The following sample code demonstrates this approach.

  • 将环境分配到 Startup 类中的属性。Assign the environment to a property in the Startup class. 使用属性(例如 if (Environment.IsDevelopment()))检查环境。Check the environment using the property (for example, if (Environment.IsDevelopment())).

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
    IConfiguration config)
{
    if (env.IsDevelopment())
    {
        app.Run(async (context) =>
        {
            var sb = new StringBuilder();
            var nl = System.Environment.NewLine;
            var rule = string.Concat(nl, new string('-', 40), nl);
            var authSchemeProvider = app.ApplicationServices
                .GetRequiredService<IAuthenticationSchemeProvider>();

            sb.Append($"Request{rule}");
            sb.Append($"{DateTimeOffset.Now}{nl}");
            sb.Append($"{context.Request.Method} {context.Request.Path}{nl}");
            sb.Append($"Scheme: {context.Request.Scheme}{nl}");
            sb.Append($"Host: {context.Request.Headers["Host"]}{nl}");
            sb.Append($"PathBase: {context.Request.PathBase.Value}{nl}");
            sb.Append($"Path: {context.Request.Path.Value}{nl}");
            sb.Append($"Query: {context.Request.QueryString.Value}{nl}{nl}");

            sb.Append($"Connection{rule}");
            sb.Append($"RemoteIp: {context.Connection.RemoteIpAddress}{nl}");
            sb.Append($"RemotePort: {context.Connection.RemotePort}{nl}");
            sb.Append($"LocalIp: {context.Connection.LocalIpAddress}{nl}");
            sb.Append($"LocalPort: {context.Connection.LocalPort}{nl}");
            sb.Append($"ClientCert: {context.Connection.ClientCertificate}{nl}{nl}");

            sb.Append($"Identity{rule}");
            sb.Append($"User: {context.User.Identity.Name}{nl}");
            var scheme = await authSchemeProvider
                .GetSchemeAsync(IISDefaults.AuthenticationScheme);
            sb.Append($"DisplayName: {scheme?.DisplayName}{nl}{nl}");

            sb.Append($"Headers{rule}");
            foreach (var header in context.Request.Headers)
            {
                sb.Append($"{header.Key}: {header.Value}{nl}");
            }
            sb.Append(nl);

            sb.Append($"Websockets{rule}");
            if (context.Features.Get<IHttpUpgradeFeature>() != null)
            {
                sb.Append($"Status: Enabled{nl}{nl}");
            }
            else
            {
                sb.Append($"Status: Disabled{nl}{nl}");
            }

            sb.Append($"Configuration{rule}");
            foreach (var pair in config.AsEnumerable())
            {
                sb.Append($"{pair.Path}: {pair.Value}{nl}");
            }
            sb.Append(nl);

            sb.Append($"Environment Variables{rule}");
            var vars = System.Environment.GetEnvironmentVariables();
            foreach (var key in vars.Keys.Cast<string>().OrderBy(key => key, 
                StringComparer.OrdinalIgnoreCase))
            {
                var value = vars[key];
                sb.Append($"{key}: {value}{nl}");
            }

            context.Response.ContentType = "text/plain";
            await context.Response.WriteAsync(sb.ToString());
        });
    }
}

调试 ASP.NET Core 应用Debug ASP.NET Core apps

以下链接提供有关 ASP.NET Core 应用程序进行调试的信息。The following links provide information on debugging ASP.NET Core apps.