我試圖在我的 Asp.net 核心 mvc 網頁上實作一個全域錯誤處理程式。為此,我創建了一個錯誤處理程式中間件,如本博文中所述。
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
response.ContentType = "application/json";
switch (error)
{
case KeyNotFoundException e:
// not found error
response.StatusCode = (int)HttpStatusCode.NotFound;
break;
default:
// unhandled error
response.StatusCode = (int)HttpStatusCode.InternalServerError;
break;
}
var result = JsonSerializer.Serialize(new { message = error?.Message });
await response.WriteAsync(result);
context.Request.Path = $"/error/{response.StatusCode}"; // <----does not work!
}
}
}
中間件按預期作業并捕獲錯誤。結果,我得到了一個帶有錯誤訊息的白頁。但我無法顯示自定義錯誤頁面。我使用以下代碼行進行了嘗試。但這不起作用。
context.Request.Path = $"/error/{response.StatusCode}";
有什么想法可以實作我的目標嗎?
提前致謝
uj5u.com熱心網友回復:
您似乎希望將瀏覽器重定向到錯誤頁面。
為此,您需要替換:
context.Request.Path = $"/error/{response.StatusCode}";
和
context.Reponse.Redirect($"/error/{response.StatusCode}");
此外,由于您要發送重定向,因此回應內容需要為空,因此也請洗掉該response.WriteAsync位。
var result = JsonSerializer.Serialize(new { message = error?.Message });
await response.WriteAsync(result);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371317.html
標籤:C# 网站 asp.net核心 网络 asp.net-core-mvc
上一篇:.net5剃刀頁面路由
