簡體   English   中英

在 ASP.NET Core 2 中使用 UseExceptionHandler() 和 API 處理和 404 處理

[英]using UseExceptionHandler() with API handling and 404 handling in ASP.NET Core 2

我有以下情況:

  • ASP.NET 核心 2 服務於/api/*上的 api 請求
  • ASP.NET Core 2 在/health上服務健康請求
  • ASP.NET Core 2 在/svc/*上服務代理請求
  • ASP.NET Core 2 在/app/上提供 SPA(如果您將 go 指向example.com ,它將提供來自/app/文件夾的文件。

現在,如果有人請求一個不存在的實體,則會引發異常。 這是通過使用 Startup.cs 中的以下內容來處理的

app.UseExceptionHandler("/error");

ErrorController 處理這些異常並返回NotFound()BadRequest()等內容。最后,它們都是 JSON 響應。

現在,如果您從 go 到/hshfdhfgh url,這將導致一個空的 404 頁面,因為沒有匹配項。 但我想做的是能夠為錯誤頁面添加一些自定義 HTML 視圖。 也許與 Razor 頁面或其他東西。

我已經查過了,建議您使用UseExceptionHandler("/error")方法,這樣您就可以返回一些視圖。 但這會與我的 JSON 響應沖突!

我唯一能想到的是:

if request does not start with /health, /svc/, /, /app or /api/
    app.UseExceptionHandler("/error/404");
else
    app.UseExceptionHandler("/error");

但這感覺很hacky。 還有其他方法嗎?

而且,向我的項目添加 razor 支持的最佳/最簡單方法是什么? 目前它沒有。

您可以以此為起點(它是 netcore 3.1,但我認為從 2 遷移時我們不必進行重大更改)。 It feels hacky and it's pain to get the handler itself right, and to put it at the exactly right place in Startup (especially if you combine it with things like dealing properly with Unauthorized responses, razor views and static files for those razor views). 但是我沒有找到更好的方法。

public static readonly PathString ApiPath = new PathString("/api");
public static readonly PathString StaticFilePath = new PathString("/site");
static bool IsApiRequestPredicate(HttpContext context) => context.Request.Path.StartsWithSegments(ApiPath, StringComparison.InvariantCulture);
static bool IsStaticFilePredicate(HttpContext context) => context.Request.Path.StartsWithSegments(StaticFilePath, StringComparison.InvariantCulture);

...

app.UseWhen(x => !IsApiRequestPredicate(x) && !IsStaticFilePredicate(x), builder =>
{
    builder.UseStatusCodePagesWithReExecute("/Error/StatusCodeViewReexecuteHandler/{0}");
    app.UseDeveloperExceptionPage();
});
app.UseWhen(x => IsApiRequestPredicate(x), builder =>
{
    builder.UseExceptionHandler("/Error/ExceptionApiReexecuteHandler");
    builder.UseStatusCodePagesWithReExecute("/Error/StatusCodeApiReexecuteHandler/{0}");
});

您也可以僅使用一個處理程序並根據 ErrorController 操作中的 OriginalPath 進行決定:

var errorFeature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
if (errorFeature.OriginalPath.StartsWith("/api", StringComparison.InvariantCulture))
{
    return BadRequest(new { error = "entity not found" });
} else {
    return View("NotFound");
}
// exceptionFeature gives you access to the exception thrown

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM