處理 ASP.NET Core API 中的錯誤

備註

這不是本文的最新版本。 關於目前版本,請參閱本文的 .NET 11 版本。

本文說明如何處理 ASP.NET Core API 中的錯誤。 已選取 [最小 API] 的檔案。 若要查看控制器基礎 API 的文件,請選擇 Controllers 標籤。關於 Blazor 錯誤處理指引,請參見 ASP.NET Core Blazor 應用程式中的錯誤處理。

開發人員例外頁面

「開發人員例外狀況頁面」會顯示未處理要求例外狀況的詳細資訊。 它會使用 DeveloperExceptionPageMiddleware 從 HTTP 管線中擷取同步和非同步例外狀況,並產生錯誤回應。 開發人員例外狀況頁面會在中介程式管線的早期執行,因此它可以攔截在後續中介程式中拋出的未處理例外狀況。

ASP.NET Core 應用程式預設啟用開發者例外頁面,當兩者同時:

使用舊版範本所建立的應用程式 (也就是使用 WebHost.CreateDefaultBuilder) 可以透過呼叫 app.UseDeveloperExceptionPage 來啟用開發人員例外狀況頁面。

警告

除非應用程式在Development環境中執行,否則不要啟用開發者例外頁面。 當應用程式在生產環境中執行時,請勿公開共用詳細的例外狀況資訊。 欲了解更多關於環境配置的資訊,請參見 ASP.NET Core runtime environments。

開發人員例外狀況頁面可以包含例外狀況和要求的下列相關資訊:

  • 堆疊追蹤
  • 查詢字串參數 (如果有的話)
  • Cookies,如果有的話
  • Headers
  • 端點中繼資料 (如果有的話)

開發人員例外狀況頁面不保證提供任何資訊。 請使用記錄來取得完整的錯誤資訊。

下圖顯示範例開發人員例外狀況頁面,其中包含動畫,以顯示索引標籤和顯示的資訊:

開發者例外頁面會動畫顯示每個選中的分頁。

為了回應具有 Accept: text/plain 標頭的要求,開發人員例外狀況頁面會傳回純文字,而不是 HTML。 例如:

Status: 500 Internal Server Error
Time: 9.39 msSize: 480 bytes
FormattedRawHeadersRequest
Body
text/plain; charset=utf-8, 480 bytes
System.InvalidOperationException: Sample Exception
   at WebApplicationMinimal.Program.<>c.<Main>b__0_0() in C:\Source\WebApplicationMinimal\Program.cs:line 12
   at lambda_method1(Closure, Object, HttpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

HEADERS
=======
Accept: text/plain
Host: localhost:7267
traceparent: 00-0eab195ea19d07b90a46cd7d6bf2f

若要在最小 API 中查看開發人員例外狀況頁面:

  • 在環境中執行範例應用程式Development。
  • 移至 /exception 端點。

本節參考下列範例應用程式,以示範在最小 API 中處理例外狀況的方法。 當請求端點 /exception 時,它會擲回例外狀況:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/exception", () => 
{
    throw new InvalidOperationException("Sample Exception");
});

app.MapGet("/", () => "Test by calling /exception");

app.Run();

例外狀況處理常式

在非開發環境中,使用 例外處理中介軟體 產生錯誤承載。

若要設定 exception handler middleware,請呼叫 UseExceptionHandler。 例如,下列程式碼會變更應用程式,使其向用戶端回應符合 RFC 7807 規範的酬載。 如需詳細資訊,請參閱本文稍後的問題 詳細資料 一節。

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseExceptionHandler(exceptionHandlerApp 
    => exceptionHandlerApp.Run(async context 
        => await Results.Problem()
                     .ExecuteAsync(context)));

app.MapGet("/exception", () => 
{
    throw new InvalidOperationException("Sample Exception");
});

app.MapGet("/", () => "Test by calling /exception");

app.Run();

用戶端和伺服器錯誤回應

請考慮下列最小 API 應用程式。

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/users/{id:int}", (int id) 
    => id <= 0 ? Results.BadRequest() : Results.Ok(new User(id)));

app.MapGet("/", () => "Test by calling /users/{id:int}");

app.Run();

public record User(int Id);

/users 端點會在 200 OK 大於 json 時產生 User,並附帶 id 的 0 表示;否則會傳回不含回應主體的 400 BAD REQUEST 狀態碼。 如需建立回應的詳細資訊,請參閱在 最小 API 應用程式中建立回應。

可將 Status Code Pages middleware 設定為在內容為空時,為所有 HTTP 用戶端(400-499)或伺服器(500 -599)回應產生通用的主體內容。 中介軟體是藉由呼叫 UseStatusCodePages 延伸模組方法來設定。

舉例來說,下列範例會變更應用程式,以符合 RFC 7807 規範的承載回應用戶端,以回應所有用戶端和伺服器回應,包括路由錯誤 (例如 404 NOT FOUND)。 如需詳細資訊,請參閱 問題詳細資料 一節。

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseStatusCodePages(async statusCodeContext 
    => await Results.Problem(statusCode: statusCodeContext.HttpContext.Response.StatusCode)
                 .ExecuteAsync(statusCodeContext.HttpContext));

app.MapGet("/users/{id:int}", (int id) 
    => id <= 0 ? Results.BadRequest() : Results.Ok(new User(id)) );

app.MapGet("/", () => "Test by calling /users/{id:int}");

app.Run();

public record User(int Id);

問題詳細資料

問題細節 並非描述 HTTP API 錯誤的唯一回應格式,但它們通常用於報告 HTTP API 的錯誤。

問題詳細服務實作了 IProblemDetailsService 介面,支援在 ASP.NET Core 中建立問題細節。 AddProblemDetails(IServiceCollection) 上的 IServiceCollection 擴充方法會註冊預設的 IProblemDetailsService 實作。

在 ASP.NET Core應用程式中,當呼叫 AddProblemDetails 時,以下中介軟體會產生問題細節 HTTP 回應,除非 Accept 請求標頭不包含註冊的 IProblemDetailsWriter(預設:application/json 所支援的內容類型):

最小 API 應用程式可使用 擴充方法,設定為針對所有 HTTP 用戶端和伺服器錯誤回應產生問題詳細資料回應,而這些回應。

下列程式碼會設定應用程式以產生問題詳細資料:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();

app.MapGet("/users/{id:int}", (int id) 
    => id <= 0 ? Results.BadRequest() : Results.Ok(new User(id)));

app.MapGet("/", () => "Test by calling /users/{id:int}");

app.Run();

public record User(int Id);

如需有關使用 AddProblemDetails的詳細資訊,請參閱 問題詳細資料

使用 RouteHandlerOptions.ThrowOnBadRequest 自訂錯誤請求處理

當最小 API 參數繫結遇到 Bad Request 錯誤(例如格式錯誤的 JSON 或型別轉換錯誤)時,錯誤處理由 ThrowOnBadRequest 控制:

  • 在 Development 環境中,預設 ThrowOnBadRequest 為 true。 不正確要求繫結失敗時會擲回一個 BadHttpRequestException,該例外會流經例外處理中介軟體(UseExceptionHandler),並呼叫已註冊的 IExceptionHandler 處理常式(可在 ASP.NET Core 8 及更新版本中使用)或自訂例外處理常式來產生 Problem Details 回應。
  • 在非開發環境中(例如 Production), ThrowOnBadRequest 預設為 false。 錯誤請求綁定失敗會直接寫入 400 Bad Request 狀態碼,而不會拋出例外,繞過自訂例外處理器。

對於 JSON 主體繫結,不支援的請求內容類型在 ThrowOnBadRequest 為 true 時會拋出 BadHttpRequestException,且 StatusCode 會設為 415;當其為 false 時,則會直接回傳 415 Unsupported Media Type。 從自訂 BindAsync 實作擲回的未處理例外,無論此設定為何,一律都會傳播。

為確保錯誤請求綁定失敗時拋出例外並觸發你在所有環境中設定的例外處理程序,請設定 ThrowOnBadRequest:

builder.Services.Configure<RouteHandlerOptions>(options =>
{
    options.ThrowOnBadRequest = true;
});

Important

當啟用 ThrowOnBadRequest 時,綁定失敗會拋出 BadHttpRequestException。 在 ASP.NET Core 11 及更新版本中,UseExceptionHandler問題細節回應預設會保留BadHttpRequestException.StatusCode。 在 ASP.NET Core 10 及更早版本中,未處理的例外狀況預設為 500 Internal Server Error,除非處理常式明確在 BadHttpRequestException.StatusCode 和產生的 Status 上都保留 HttpContext.Response.StatusCode。 會覆寫回應的自訂例外處理程序或IExceptionHandler實作(ASP.NET Core 8 及更新版本)仍應確保BadHttpRequestException.StatusCode被保留,避免客戶端錯誤被報告為伺服器故障。

IProblemDetailsService 後備

在下列程式碼中,如果 httpContext.Response.WriteAsync("Fallback: An error occurred.") 實作無法產生 IProblemDetailsService,ProblemDetails 會傳回錯誤:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

var app = builder.Build();

app.UseExceptionHandler(exceptionHandlerApp =>
{
    exceptionHandlerApp.Run(async httpContext =>
    {
        var pds = httpContext.RequestServices.GetService<IProblemDetailsService>();
        if (pds == null
            || !await pds.TryWriteAsync(new() { HttpContext = httpContext }))
        {
            // Fallback behavior
            await httpContext.Response.WriteAsync("Fallback: An error occurred.");
        }
    });
});

app.MapGet("/exception", () =>
{
    throw new InvalidOperationException("Sample Exception");
});

app.MapGet("/", () => "Test by calling /exception");

app.Run();

上述 程式碼:

  • 如果 problemDetailsService 無法寫入 ProblemDetails,則會寫入附帶後援代碼的錯誤訊息。 例如,某個端點的 Accept 要求標頭欄位 指定了 DefaultProblemDetailsWriter 不支援的媒體類型。
  • 使用 例外處理中介軟體。

備註

在 DefaultProblemDetailsWriter 請求標頭中支援以下媒體類型 Accept :

  • application/json
  • application/problem+json
  • 例如 */* 和 application/* 的萬用字元類型

非 JSON 媒體類型,如 application/xml 或 text/html, 不 被支援,並會觸發備援行為。

下列範例與上述範例類似,只是它會呼叫 Status Code Pages middleware。

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();

var app = builder.Build();

app.UseStatusCodePages(statusCodeHandlerApp =>
{
    statusCodeHandlerApp.Run(async httpContext =>
    {
        var pds = httpContext.RequestServices.GetService<IProblemDetailsService>();
        if (pds == null
            || !await pds.TryWriteAsync(new() { HttpContext = httpContext }))
        {
            // Fallback behavior
            await httpContext.Response.WriteAsync("Fallback: An error occurred.");
        }
    });
});

app.MapGet("/users/{id:int}", (int id) =>
{
    return id <= 0 ? Results.BadRequest() : Results.Ok(new User(id));
});

app.MapGet("/", () => "Test by calling /users/{id:int}");

app.Run();

public record User(int Id);

其他錯誤處理功能

從控制器移轉至最小API

如果您要從控制器型 API 移轉至最小 API:

  1. 將動作過濾器替換 為端點過濾器或中介軟體
  2. 將模型驗證替換 為手動驗證或自訂綁定
  3. 以例外處理中介軟體取代例外篩選器
  4. 設定問題詳細資料,使用 AddProblemDetails() 以提供一致的錯誤回應

使用 TypedResults 回傳多種結果類型

端點通常會根據請求結果傳回不同的結果類型,例如發生錯誤時傳回 ProblemHttpResult,或在成功時傳回 RedirectHttpResult。 為保留編譯時型別安全與強型別簽章,請使用帶有 TypedResults的聯集回傳型別Results<TResult1,TResult2>。 由於結果類型(例如 )RedirectHttpResult不會自動提供 OpenAPI 元資料,請用 和 來設定明確的回應元資料ProducesProducesProblem:

using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

bool IsSupportedProvider(string provider) => provider is "google" or "github";

app.MapGet("/login-provider",
    Results<RedirectHttpResult, ProblemHttpResult> (string? provider) =>
{
    if (string.IsNullOrEmpty(provider))
    {
        return TypedResults.Problem(
            title: "Provider not specified",
            detail: "A login provider is required.",
            statusCode: StatusCodes.Status400BadRequest);
    }

    if (!IsSupportedProvider(provider))
    {
        return TypedResults.Problem(
            title: "Provider not supported",
            detail: $"The provider '{provider}' is not supported.",
            statusCode: StatusCodes.Status400BadRequest);
    }

    return TypedResults.Redirect($"/auth/{provider}");
})
.Produces(StatusCodes.Status302Found)
.ProducesProblem(StatusCodes.Status400BadRequest);

app.Run();

使用 TypedResults with Results<TResult1,TResult2> 可避免因預期的業務錯誤拋出例外,並提供強型別回應簽名以提升可測試性。

何時使用控制器型錯誤處理

如果您需要,請考慮以控制器為基礎的 API:

  • 複雜的模型驗證案例
  • 跨多個控制器的集中式異常處理
  • 對錯誤回應格式的精細控制
  • 與篩選器和約定等 MVC 功能整合

如需控制器型錯誤處理的詳細資訊,包括驗證錯誤、問題詳細資料自訂和異常狀況篩選器, 請參閱控制器索引 標籤區段。