全局处理 Web API 2 中的异常
本文关键字:异常 API 处理 Web 全局 | 更新日期: 2023-09-27 18:33:20
我正在尝试学习和理解Web API 2中的全局异常处理。当我单步执行以下代码时,我以为我会在 Handle 方法中达到断点,但我没有。
我错过了什么?
以下是我所做的:我在Visual Studio 2013 Update 4中创建了一个新的Web API项目。在我的根目录中,我创建了以下类 - 名为GlobalExceptionHandler.cs如下所示:
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
// --> Break Point in the next line <--
string str1 = context.Exception.Message;
}
}
这是我的 Startup.cs 的样子:
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
}
}
当我尝试在我的 web api 方法中生成异常时,我期望在全局异常处理程序中点击句柄方法,但我没有。
public IHttpActionResult Get()
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
return Ok("I should not get here because of exception");
}
在 WebAPI 中,抛出 HttpResponseException 被视为返回响应。它不被视为未经处理的异常,因此不会由你注册的异常处理程序选取。尝试抛出另一种异常类型,它应该可以工作。