Asp.net-Core
Response.TrySkipIisCustomErrors 等效於 asp.net 核心?
如何防止 IIS 使用 IIS 預設錯誤頁面覆蓋自定義錯誤頁面?是否有等效於 asp.net 核心的 Response.TrySkipIisCustomErrors?在 ASP Net MVC 中,我使用下面的程式碼在沒有自定義頁面的情況下發送錯誤,但在 asp net core 中它不起作用。
try { // some code } catch (Exception ex) { Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.InternalServerError; mensagem = ex.Message; }
聽起來您正在嘗試禁用特定請求的狀態程式碼錯誤頁面。處理錯誤的ASP.NET Core 文件為您提供了答案。
它不像舊
TrySkipIisCustomErrors標誌那麼簡潔,但可能更清楚實際發生了什麼:var statusCodePagesFeature = HttpContext.Features.Get<IStatusCodePagesFeature>(); if (statusCodePagesFeature is not null) { statusCodePagesFeature.Enabled = false; }
您可以嘗試編寫一個
exception處理中間件。這是我用來參考的部落格文章。類似的東西public class ErrorHandlingMiddleware { private readonly RequestDelegate next; public ErrorHandlingMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { try { await next(context); } catch (Exception ex) { await CustomHandleExceptionAsync(context, ex); } } private static Task CustomHandleExceptionAsync(HttpContext context, Exception exception) { if (exception is NotFoundException) { var customJson = JsonConvert.SerializeObject(new{ error = exception.Message }); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.NotFound; return context.Response.WriteAsync(customJson); } }