Logo

dev-resources.site

for different kinds of informations.

[ASP.NET] 如何導向到錯誤頁面

Published at
12/11/2024
Categories
aspnet
Author
fakestandard
Categories
1 categories in total
aspnet
open
Author
12 person written this
fakestandard
open
[ASP.NET] 如何導向到錯誤頁面

近期遇到客戶要求對網站進行弱點掃描,報告中其中一項是 Server Error Message,意思是當發生錯誤時,白底黃框的錯誤訊息會直接呈現給使用者,若是給一般使用者看到頂多得到觀感不佳的回饋,要是給 Hacker 看到,網站危險性一下就提升好幾個檔次,所以程式在運行過程發生錯誤時,應導向至錯誤畫面,而非暴露赤裸裸的錯誤資訊。

所以說,發生錯誤時要如何導向到錯誤頁面?自己寫 RedirectToAction?

其實 ASP.NET MVC 預設會在 FilterConfig.cs 中註冊 HandleErrorAttribute,也就是當發生 Http Status Code 500 時會交給 HandleErrorAttribute 去處理,它的功用是當程式部署後,倘若發生錯誤就會導向到 Error.cshtml,使用者就不會看到詳細錯誤資訊。不過在開發環境中還是可以看到詳細的錯誤資訊。

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        // 預設註冊
        filters.Add(new HandleErrorAttribute());
    }
}
Enter fullscreen mode Exit fullscreen mode

要讓頁面成功導向到錯誤頁面,try catch 基本功不可少,當 Exception 發生時會呼叫 HandleErrorAttribute 裡的 OnException,OnException 會將畫面導向到預設的錯誤頁面,也就是 Error。有興趣的朋友可以喵一眼 OnException 的 Source Code

//
// Summary:
//     Called when an exception occurs.
//
// Parameters:
//   filterContext:
//     The action-filter context.
//
// Exceptions:
//   T:System.ArgumentNullException:
//     The filterContext parameter is null.
public virtual void OnException(ExceptionContext filterContext)
{
    if (filterContext == null)
    {
        throw new ArgumentNullException("filterContext");
    }

    if (!filterContext.IsChildAction && !filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled)
    {
        Exception exception = filterContext.Exception;
        if (new HttpException(null, exception).GetHttpCode() == 500 && ExceptionType.IsInstanceOfType(exception))
        {
            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            filterContext.Result = new ViewResult
            {
                ViewName = View,
                MasterName = Master,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

試著引發錯誤訊息讓畫面導向到 Error Page。

public ActionResult Index()
{
    try
    {
        // 刻意引發錯誤訊息
        throw new Exception();

        return View();
    }
    catch (Exception ex)
    {
        throw;
    }
}
Enter fullscreen mode Exit fullscreen mode

打完,收工!


Thanks for reading the article 🌷 🌻 🌼

If you like it, please don't hesitate to click heart button ❤️
or follow my GitHub ⭐ I'd appreciate it.


aspnet Article's
30 articles in total
Favicon
The Future of ASP.NET: What to Expect
Favicon
DevExpress - Enhancing ASP.NET Web Forms with the ASPxGridView Control
Favicon
Advanced Search in .NET with Elasticsearch(Full Video)
Favicon
Introducing Brick SaaS Starter Kit - Launch SaaS Products Faster
Favicon
Using server sent events in ASP.NET
Favicon
Important Links
Favicon
Serverless OAuth2/OIDC server with OpenIddict 6 and RDS Aurora v2
Favicon
Learning in Reverse: How I Would Learn ASP. Net Core and Entity Framework If I Could Go Back In Time
Favicon
Dependency injection validation error in ASP.NET Core projects
Favicon
Agrupamiento de datos de una lista usando LINQ en C#
Favicon
Asp .Net: Create a Simple 'Web User Control'
Favicon
[ASP.NET] 如何導向到錯誤頁面
Favicon
DevExpress - Simplifying Server-to-Client Data Transfer with ASPxCallback JSProperties
Favicon
Asp.net
Favicon
[ASP.NET] 設置與取得 Web.config 自定義資料
Favicon
How to Hire Dedicated .NET Developers
Favicon
Permission-Based Authorization in ASP.NET Core: A Step-by-Step Guide
Favicon
Permission-Based Authorization in ASP.NET Core: A Step-by-Step Guide
Favicon
Dependency Container and Services Lifetimes (На русском)
Favicon
Containerize ASP.NET Core API, Entity Framework with SQL Server, Let's Encrypt, Docker, and Nginx (Part 1)
Favicon
differences of Transient and scoped in ASP NET
Favicon
ASP.NET8 using DataTables.net – Part6 – Returning additional parameters in AJAX
Favicon
ASP.NET8 using DataTables.net – Part4 – Multilingual
Favicon
ASP.NET8 using DataTables.net – Part8 – Select rows
Favicon
ASP.NET8 using DataTables.net – Part3 – State saving
Favicon
ASP.NET8 using DataTables.net – Part7 – Buttons regular
Favicon
ASP.NET8 using DataTables.net – Part5 – Passing additional parameters in AJAX
Favicon
ASP.NET8 using DataTables.net – Part9 – Advanced Filters
Favicon
ASP.NET8 using DataTables.net – Part2 – Action buttons
Favicon
ASP.NET 8 – Multilingual Application with single Resx file – Part 3 – Forms Validation Strings

Featured ones: