我正在尝试学习和理解Web 2中的全局异常处理。当我逐步完成下面的代码时,我以为我已经在Handle方法中碰到了我的断点,但我没有。
我遗漏了什么?
下面是我所做的工作:我在VisualStudio2013Update 4中创建了一个新的Web项目。在根目录中,我创建了如下类--名为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方法中生成一个异常时,我希望在GlobalExceptionHandler中点击Handle方法,但我没有。
public IHttpActionResult Get()
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
return Ok("I should not get here because of exception");
}发布于 2014-12-05 04:55:37
在WebApi中,抛出一个HttpResponseException被认为返回一个响应。它不是一个未处理的异常,因此不会被您注册的异常处理程序获取。尝试抛出另一种异常类型,它应该可以工作。
https://stackoverflow.com/questions/27308658
复制相似问题