[英]Custom error handling middleware in ASP.NET Core 3.1?
我正在 ASP.NET Core 3.1 中開發一個項目。 通過使用由 4 個不同層組成的干凈架構,即持久性 - 域 - 應用程序 - Web。
In the Web layer, I have an Admin area which is going to be made with React and also I have an online store which will be using this Admin area but it will be made as an html online store without using REST API. 我的 REST API 路線是這樣的: localhost:5001/api/v1/...
我想知道,當我的 REST API 出現錯誤時,我如何制作一個自定義錯誤處理中間件,它能夠發送狀態代碼和錯誤消息為 json,並且能夠同時發送它們,當 html 頁面出現錯誤時,html 查看不使用 REST API 的頁面。
我沒有測試過這段代碼,但是,您如何看待使用 customExceptions 然后根據拋出的異常處理您的響應?
public async Task Invoke(HttpContext httpContext)
{
try {
await _next.Invoke(httpContext);
}
catch (RestApiException ex) {
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
httpContext.Response.ContentType = "application/json";
string jsonString = JsonConvert.SerializeObject(ex.Message);
await httpContext.Response.WriteAsync(jsonString, Encoding.UTF8)
}
catch (HtmlPagesException ex)
{
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
//write the html response to the body -> I don't know how to do this yet.
}
}
一種方法是按路徑區分請求。
在您的Configure
方法中:
app.UseWhen(o => !o.Request.Path.StartsWithSegments("/api", StringComparison.InvariantCultureIgnoreCase),
builder =>
{
builder.UseStatusCodePagesWithReExecute("/Error/{0}");
}
);
這假設您的 API 控制器標有[ApiController]
屬性,並且您至少使用 2.2 的兼容版本,這將呈現 JSON 問題詳細信息 (RFC7807)。
編輯:無意中遺漏了 HTML 部分。 您還需要一個 controller 操作來路由錯誤代碼以呈現 HTML 結果。 就像是
[AllowAnonymous]
[Route("/Error/{code:int?}")]
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error(int? code)
{
ViewBag.Code = code.GetValueOrDefault(500);
return View();
}
和一個匹配的 Razor 頁面,例如
<h1>Error @(ViewBag.Code ?? 500)</h1>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.