我正在编写.net core 3.0 Web API并尝试设置全局错误处理。根据文档,这应该是一个简单的任务,但我无法使其正常工作。我应该将我的Error方法重定向到,永远不会在抛出异常时命中设置的断点。您能告诉我我做错了什么,以及如何在我的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();
}
找到了问题和解决方案。
问题:最初,我会在Web api项目中从vs中按f5键以在调试模式下运行。在显示的Web浏览器的url中,我将放置controller方法的参数并将其发布到我的控制器。该例程导致调试器在我抛出错误的位置中断,并且不会在我在全局错误方法中的中断点处中断。
解决方案:我使用失眠症或邮递员之类的外部测试工具可以很好地工作,以测试Web API调用。我按f5键从Visual Studio中以调试模式运行Web api项目,然后转移到失眠状态并发布到控制器方法,它在我的断点处陷入全局错误方法中。因此,您必须使用外部客户端来命中控制器,才能在全局错误方法中命中断点。