将开发人员异常页面显示为 IActionResult
Posted
技术标签:
【中文标题】将开发人员异常页面显示为 IActionResult【英文标题】:Show developer exception page as IActionResult 【发布时间】:2021-11-04 19:00:22 【问题描述】:在Startup.cs
我有以下代码:
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseExceptionHandler("/Error");
app.UseHsts();
我希望我的应用程序在部署期间仍向管理员用户显示开发者异常页面。
在我的 Error.cshtml.cs 中,我想要如下内容:
public IActionResult OnGet()
if (Request.Cookies["admin"] == ReadonlyJsonService.Root.adminCookie)
// Show developer exception page.
else
// Render Error.cshtml as would happen if I had just put 'public void OnGet() '
【问题讨论】:
【参考方案1】:为什么不创建自定义中间件?
这里我们创建 AppExceptionHandlerMiddleware。如果您在开发环境中或者您有管理员 cookie,它会显示异常详细信息。
AppExceptionHandlerMiddleware.cs
public class AppExceptionHandlerMiddleware
private readonly RequestDelegate _next;
private readonly IWebHostEnvironment _env;
private readonly DeveloperExceptionPageMiddleware developerExceptionPageMiddleware;
private readonly ExceptionHandlerMiddleware exceptionHandlerMiddleware;
public AppExceptionHandlerMiddleware(RequestDelegate next, IOptions<DeveloperExceptionPageOptions> dexhOptions,
IOptions<ExceptionHandlerOptions> exhOptions, ILoggerFactory loggerFactory, IWebHostEnvironment env,
DiagnosticListener diagnosticListener, DiagnosticSource diagnosticSource, IEnumerable<IDeveloperPageExceptionFilter> filters)
_next = next;
_env = env;
developerExceptionPageMiddleware = new DeveloperExceptionPageMiddleware(next, dexhOptions, loggerFactory, env, diagnosticSource, filters);
exceptionHandlerMiddleware = new ExceptionHandlerMiddleware(next, loggerFactory, exhOptions, diagnosticListener);
public async Task Invoke(HttpContext context)
if (context.Request.Cookies["admin"] == ReadonlyJsonService.Root.adminCookie || _env.IsDevelopment())
await developerExceptionPageMiddleware.Invoke(context);
else
await exceptionHandlerMiddleware.Invoke(context);
AppExceptionHandlerExtensions.cs
public static class AppExceptionHandlerExtensions
public static IApplicationBuilder UseAppExceptionHandler(
this IApplicationBuilder builder)
return builder.UseMiddleware<AppExceptionHandlerMiddleware>();
Startup.cs
public void ConfigureServices(IServiceCollection services)
...
//Config ExceptionHandlerMiddlewareOption via DI.
services.Configure<ExceptionHandlerOptions>(option =>
option.ExceptionHandlingPath = new PathString("/Error");
);
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
app.UseAppExceptionHandler();
...
【讨论】:
完全按照要求工作。密钥是DeveloperExceptionPageMiddleware
。以上是关于将开发人员异常页面显示为 IActionResult的主要内容,如果未能解决你的问题,请参考以下文章
[六] ASP.NET Core 开发人员异常页面和环境变量
IE开发人员工具显示异常,IE加载百度地图,BMap“未定义”