-
Notifications
You must be signed in to change notification settings - Fork 353
Description
- I am using the ActionFilterAttribute to implement my model validation as introduced in Model Validation in ASP.NET Web API.
I did security hash check for my parameters, and exception happened here
public class ValidateModelAttribute : ActionFilterAttribute
{
public override async void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
else
{
var request = actionContext.Request;
HttpResponseMessage responseMessage = new HttpResponseMessage();
//security hash check logic here (Exception happens here)
//and the StatusCode will be set after checking
if (!responseMessage.IsSuccessStatusCode)
{
actionContext.Response = responseMessage;
}
}
}
}
However, the global exception handler did not catch this exception and write a text log as expected. Inherit from ExceptionHandler to write txt log.
- When I check the source code of ActionFilterAttribute, I find code like this:
public virtual Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
try
{
OnActionExecuting(actionContext);
}
catch (Exception ex)
{
return TaskHelpers.FromError(ex);
}
return TaskHelpers.Completed();
}
- I guess you might hide the exception by catch block, so I inherit the ActionFilterAttribute and override the
OnActionExecutingAsync method.
//I have copy the source code of TaskHelpers to my local project
public class CustomActionFilterAttribute : ActionFilterAttribute
{
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
try
{
OnActionExecuting(actionContext);
}
catch (Exception ex)
{
//CreateLog(LogLevel.Error, ex); //write exception log to txt
return TaskHelpers.FromError(ex);
}
return TaskHelpers.Completed();
}
}
Then I make ValidateModelAttribute inherit from the new created CustomActionFilterAttribute, then I try to debug the exception.
Before execute the OnActionExecuting in ValidateModelAttribute, it first execute OnActionExecutingAsync in CustomActionFilterAttribute. And the exception throwed from OnActionExecuting of ValidateModelAttribute, and it supposed to be caught in OnActionExecutingAsync of CustomActionFilterAttribute.
However, when I hit F11 to debug, the exception just disappeared and finish the OnActionExecuting(actionContext)
. How could it be possible?
Who knows something about this weird thing?