.net core 3.0应用程序.UseExceptionHandler未达到Error方法中的断点



我正在编程一个.net核心3.0 web api,并试图设置全局错误处理。根据文档,这应该是一项简单的任务,但我无法让它发挥作用。当我抛出异常时,我应该重定向到的Error方法永远不会达到我在其中设置的断点。你能告诉我我做错了什么,以及如何在我的错误方法中找到断点吗?

这是我的代码:

// startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseExceptionHandler("/System/Error");
app.UseStatusCodePages();
app.UseStatusCodePagesWithReExecute("/system/error/{0}");
}
// SystemController.Error method
public IActionResult Error(
[Bind(Prefix = "id")] int statusCode = 0
)
{
// break point never hits here and I want it to
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionFeature != null)
{
// Get which route the exception occurred at   
string routeWhereExceptionOccurred = exceptionFeature.Path;
// Get the exception that occurred   
Exception exceptionThatOccurred = exceptionFeature.Error;
// TODO: Do something with the exception   
// Log it with Serilog?   
}
return View();
}

找到了问题和解决方案。

问题:最初我会在我的webapi项目中从vs中按f5,以在调试模式下运行。在显示的网络浏览器的url中,我会放置控制器方法的参数,并将其发布到我的控制器。这个例程导致调试器在我抛出错误的地方中断,而不会在全局错误方法中的中断点中断。

解决方案:我使用失眠或邮递员之类的外部测试工具来测试web API调用,这样做很好。我按f5从Visual Studio中以调试模式运行web api项目,然后转到失眠并发布到控制器方法,它在我的断点处中断了全局错误方法。因此,您必须使用外部客户端来命中控制器,以便在全局错误方法中命中断点。

最新更新