如何将server exception(服务器异常)展示在Razor Pages错误页
Error.cshtml 展示服务器错误信息实现思路
注:以下方案仅为临时排查使用,排查完成后务必立即关闭相关配置、删除展示代码,避免敏感信息泄露。
前置配置确认
- 确认你框架对应的自定义错误配置,已开启异常信息传递通道,不要设置为拦截所有异常详情传递。
方案1:ASP.NET MVC(.NET Framework)场景
- 在
Global.asax.cs的Application_Error全局事件中捕获异常,存入Session或HttpContext.Items:
protected void Application_Error(object sender, EventArgs e) { Exception currentEx = Server.GetLastError(); if (currentEx != null) { // 使用Response.Redirect跳转的话存Session,用Server.Transfer跳转可以直接存在HttpContext.Items Session["LatestUnhandledException"] = currentEx; } }
- 在Error.cshtml中直接读取存储的异常,展示需要的字段:
@{ Exception ex = Session["LatestUnhandledException"] as Exception; if (ex != null) { <p>异常类型:@ex.GetType().FullName</p> <p>异常信息:@ex.Message</p> <p>堆栈跟踪:<pre>@ex.StackTrace</pre></p> @if (ex.InnerException != null) { <p>内部异常信息:@ex.InnerException.Message</p> <p>内部异常堆栈:<pre>@ex.InnerException.StackTrace</pre></p> } // 读取完立即清除存储的异常,避免后续误泄露 Session.Remove("LatestUnhandledException"); } }
方案2:ASP.NET Core 场景
- 先在
Program.cs中保留异常处理中间件的默认配置,不要额外拦截异常传递:
if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); // 临时调试阶段可以注释HSTS、强制跳转等配置避免干扰 // app.UseHsts(); }
- 在Error.cshtml对应的PageModel(Error.cshtml.cs)中注入服务获取异常:
using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Mvc.RazorPages; public class ErrorModel : PageModel { public Exception? UnhandledException { get; set; } public string? ErrorRequestPath { get; set; } public void OnGet() { var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>(); if (exceptionFeature != null) { UnhandledException = exceptionFeature.Error; ErrorRequestPath = exceptionFeature.Path; } } }
- 在Error.cshtml中渲染异常信息:
@page @model ErrorModel @{ if (Model.UnhandledException != null) { <p>出错请求路径:@Model.ErrorRequestPath</p> <p>异常类型:@Model.UnhandledException.GetType().FullName</p> <p>异常信息:@Model.UnhandledException.Message</p> <p>堆栈跟踪:<pre>@Model.UnhandledException.StackTrace</pre></p> @if (Model.UnhandledException.InnerException != null) { <p>内部异常信息:@Model.UnhandledException.InnerException.Message</p> } } }
临时使用注意事项
- 可以额外加IP白名单校验,只有你自己的访问IP能看到异常详情,避免公网用户拿到敏感信息
- 排查完成后立即删除所有异常展示代码,恢复生产环境的错误页配置
- 不要把包含数据库连接串、接口密钥、内部服务地址的堆栈信息暴露在公网环境
内容的提问来源于stack exchange,提问作者chandler
相关产品推荐
相关产品推荐

