I'm using an action filter for handling exceptions inside my ApiController methods.
My methods return results as JSON using return Ok(object) however when I want to handle exceptions in my Action Filter for handling exception of my ApiController methods, it does not have access to Ok method to serialize objects as JSON since it is a protected method inside ApiController.
Here is a sample of my action filter:
public class WebServiceExceptionFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
Exception exception = filterContext.Exception;
if (exception is DbEntityValidationException)
{
List<string> errorMessageList = generateValidationErrorMessageList((DbEntityValidationException)e);
string detailedError = String.Join(" ; ", errorMessageList);
filterContext.Result = Ok(new WebServiceResult(ErrorCodes.ERROR_CODE_MINUS_3002_DB_VALIDATION, detailedError));
//---------------------^^ Ok is not available ------
}
}
}
You can't use Ok because that is a ControllerBase Object and you can't use Controller as a base class for your ActionFilter. What you can do is set the status code of your filterContext.HttpContext like this:
or use a custom statusCode (like 500) instead of exception.StatusCode