gpt4 book ai didi

c# - ASP.NET Core Razor - 全局异常处理程序

转载 作者:行者123 更新时间:2023-12-05 04:55:56 32 4
gpt4 key购买 nike

我有以下部分在 .cshtml.cs 但不是 .cshtml 文件中工作:

我是否需要更改我的 GlobalExceptionFilter 或我是否需要添加其他内容来捕获 .cshtml 错误?

对于这两个错误,他们都会重定向到/Error 页面。

public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
LogError(context.Exception);
}
}

Startup.cs中:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvcOptions(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
});
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
}

Index.cshtml.cs 中:

public void OnGet()
{
throw new Exception("Test"); //This hits GlobalExceptionFilter
}

Index.cshtml 中:

@{
throw new Exception("Test"); //This does NOT hit GlobalExceptionFilter
}

提前致谢

最佳答案

Exception filters apply global policies to unhandled exceptions that occur before the response body has been written to.

Exception filters:

Are good for trapping exceptions that occur within actions.

Are not as flexible as error handling middleware.

doc可以看出.

在这里您可以使用自定义的 ExceptionHandler 中间件,如下所示:

public class CustomExceptionHandler
{
private readonly IWebHostEnvironment _environment;

public CustomExceptionHandler(IWebHostEnvironment environment)
{
_environment = environment;
}

public async Task Invoke(HttpContext httpContext)
{
var feature = httpContext.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>();
var error = feature?.Error;

if(error != null)
{
LogError(error);
throw error;
}

await Task.CompletedTask;
}
}

在startup.cs中使用

app.UseExceptionHandler(new ExceptionHandlerOptions
{
ExceptionHandler = new CustomExceptionHandler(env).Invoke
});

关于c# - ASP.NET Core Razor - 全局异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65126431/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com