首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未引发Webapi 2全局异常处理

未引发Webapi 2全局异常处理
EN

Stack Overflow用户
提问于 2017-05-05 11:10:24
回答 1查看 412关注 0票数 0

我正在使用web 2来为客户开发服务,管理我们正在使用的ExceptionsFilterAttribute错误,但正如您所知,在这个级别上并不是所有的例外都会被捕获。在protected void Application_AuthenticateRequest(Object sender, EventArgs e)中会引发一些错误,我希望处理这些错误并向我们的客户端发送一条自定义消息,以便向他提供有关错误的更多细节,为了解决这个问题,我创建了一个GlobalExceptionHandler

代码语言:javascript
复制
  public class GlobalExceptionHandler: ExceptionHandler
{
//A basic DTO to return back to the caller with data about the error
private class ErrorInformation
{
public string Message { get; set; }
public DateTime ErrorDate { get; set; }
}

public override void Handle(ExceptionHandlerContext context)
{

//Return a DTO representing what happened
context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError,
new ErrorInformation { Message="We apologize but an unexpected error occured. Please try again later.", ErrorDate=DateTime.UtcNow }));

//This is commented out, but could also serve the purpose if you wanted to only return some text directly, rather than JSON that the front end will bind to.
//context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, "We apologize but an unexpected error occured. Please try again later."));
}
}

在WebApiConfig中,我添加了以下一行:

代码语言:javascript
复制
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());

Application_AuthenticateRequest会引发一些错误,但从未到达GlobalExceptionHandler

你知道我怎么解决这个问题吗?

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-05 20:12:49

Application_AuthenticateRequest没有出现在Web管道中。因此,如果在此方法中抛出异常,这些异常可以被Web异常处理程序捕获,因为异常是在Web管道启动之前抛出的。

有两种方法可以做到这一点:

  1. 要么更改身份验证机制,使用Web身份验证(IAuthenticationFilter)而不是Application_AuthenticateRequest。
代码语言:javascript
复制
- If this project has only Web API related controllers, not like MVC and all.

  1. 或者在Application_Error文件中使用Global.asax.cs捕获在Application_AuthenticateRequest中引发的异常
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43803455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档