Using Ok outside of ApiController, inside ActionFilter

616 Views Asked by At

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 ------
        }

    }
}
2

There are 2 best solutions below

0
Fabian Claasen On

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:

filterContext.HttpContext.Response.StatusCode = exception.StatusCode;

or use a custom statusCode (like 500) instead of exception.StatusCode

0
Alexander On

According to the source code of ControllerBase returning Ok result from Controller is simply returning OkObjectResult instance.

[NonAction]
public virtual OkObjectResult Ok([ActionResultObjectValue] object value)
    => new OkObjectResult(value);

So you can set it directly to filterContext.Result

var result = new WebServiceResult(ErrorCodes.ERROR_CODE_MINUS_3002_DB_VALIDATION, detailedError);
filterContext.Result = new OkObjectResult(result);