gpt4 book ai didi

c# - webapi 2 全局异常处理,controller-context 为空

转载 作者:太空狗 更新时间:2023-10-29 21:43:31 24 4
gpt4 key购买 nike

在 WebAPI 2 全局异常处理程序中,我试图从抛出错误的地方获取 Controller 对象的引用。

下面是它的代码:

public class CustomExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var controller = context.ExceptionContext.ControllerContext;
var action = context.ExceptionContext.ActionContext;

//.....some code after this
}
}
上面的

controlleraction 变量结果为空。

有什么建议吗?

最佳答案

假设异常是从操作方法中抛出的。

确保从 ExceptionHandlerShouldHandle 方法返回 true
否则,Handle 方法中的 context.ExceptionContext.ControllerContext 将为 null。

出于某种原因,context.ExceptionContext.ActionContext 始终为 null,但是这个可以通过 Controller 属性从 HttpControllerContext 中检索。

class MyExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
HttpControllerContext controllerContext = context.ExceptionContext.ControllerContext;
if (controllerContext != null)
{
System.Web.Http.ApiController apiController = controllerContext.Controller as ApiController;
if (apiController != null)
{
HttpActionContext actionContext = apiController.ActionContext;
// ...
}
}

// ...

base.Handle(context);
}

public override Boolean ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
}

如果您只关心异常日志记录,请选择 ExceptionLogger 而不是 ExceptionHandler
参见 MSDN .

Exception loggers are the solution to seeing all unhandled exception caught by Web API.
Exception loggers always get called, even if we're about to abort the connection.
Exception handlers only get called when we're still able to choose which response message to send.

同样,如上所示,从 HttpControllerContext 中检索 HttpActionContext

关于c# - webapi 2 全局异常处理,controller-context 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com