You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ASP.NET Core的Staging/Production环境本地显示详细错误?

在本地运行Staging/Production环境时显示详细错误信息的方法

以下是几种无需临时修改配置文件名的解决方案:

方法1:根据环境条件启用开发者异常页

在Program.cs中,根据当前运行环境判断,为Staging(或本地运行的Production)开启开发者异常页:

var builder = WebApplication.CreateBuilder(args);

// 其他服务配置...

var app = builder.Build();

// 环境判断逻辑
if (app.Environment.IsDevelopment() || app.Environment.IsStaging())
{
    // 为Staging环境启用详细错误页
    app.UseDeveloperExceptionPage();
}
else
{
    // 生产环境保留通用错误页
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

// 其他中间件配置...

app.Run();

如果需要仅在本地运行Staging/Production时开启,可以额外结合本地标识(比如读取一个专属本地的配置项)来缩小生效范围。

方法2:通过launchSettings.json启用详细错误

在launchSettings.json中,为Staging/Production的配置添加ASPNETCORE_DETAILEDERRORS环境变量,强制开启详细错误:

{
  "profiles": {
    "TestApp-Staging": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging",
        "ASPNETCORE_DETAILEDERRORS": "true"
      }
    },
    "TestApp-Production": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5002;http://localhost:5003",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production",
        "ASPNETCORE_DETAILEDERRORS": "true"
      }
    }
  }
}

这个变量会强制ASP.NET Core输出详细错误信息,无需修改中间件配置。

方法3:通过环境配置文件控制

在appsettings.Staging.json中添加配置项:

{
  "DetailedErrors": true
}

然后在Program.cs中读取该配置,决定是否启用开发者异常页:

var builder = WebApplication.CreateBuilder(args);

// 绑定配置
var detailedErrors = builder.Configuration.GetValue<bool>("DetailedErrors");

// 其他服务配置...

var app = builder.Build();

if (app.Environment.IsDevelopment() || detailedErrors)
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

// 其他中间件配置...

app.Run();

这种方式更灵活,可以通过配置文件开关详细错误,无需改动代码。

内容的提问来源于stack exchange,提问作者Milacay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 15:27:08