问题
I've built a simple REST service using ASP.NET web api.
I've associated one of my controller's method with a custom ActionFilterAttribute, overriding it's OnActionExecuted. On the action filter I use the response about to be sent (actionExecutedContext.Response).
The whole application is associated with a custom ExceptionFilterAttribute overriding OnException used for logging errors.
Now for the problem - when an exception is raised from the controller's method, I've expected one of the two :
1. The OnException will be fired away first, then the OnActionExcuted with an appropriate response.
2. Only the OnExcpetion is invoked, since the action didn't really finished executing.
What actually happens is that the OnActionExecuted is invoked, the response is null, as a result another exception (this time null reference) is raised, caught in the OnException and loggs the wrong exception.
My questions are :
1. Why is the OnActionExecuted is called if an exception has been raised? Shouldn't the OnException be invoked first? An explanation will be appriciated.
2. I understand that OnActionExecuted should be changed, what's the right way to do it? In general do I need to check before doing anything that the actionExecutedContext.Response or the actionExecutedContext.Exception isn't null (besides the obvious check in the OnException methods)? I've based my code in the attributes' actions that there's always a response but apparently not.
Any help would be appriciated, thanks in advance :)!
来源:https://stackoverflow.com/questions/19870461/web-api-rest-service-exception-handling-issue