Asp.net Web API - return data from actionfilter

All you need is to assign the Response:

public class MyActionFilterAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        actionContext.Response = actionContext.Request.CreateResponse(
            HttpStatusCode.OK, 
            new { foo = "bar" }, 
            actionContext.ControllerContext.Configuration.Formatters.JsonFormatter
        );
    }
}

Assuming the following controller action:

[MyActionFilter]
public string Get()
{
    return "OK";
}

this custom action filter will short-circuit the execution of the action and directly return the response we provided.


Just throwing this out there in case anyone else comes here like me and doesn't find an answer to their problem:

You may be using the wrong import - You have 2 options:

  • System.Web.Http.Filters
  • System.Web.Mvc (or System.Web.Http.Mvc)

Courtesy of Troy Dai from this question: Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not firing?


you can use HttpResponseMessage to create the response like that

var output =  new Result() { Status = Status.Error.ToString(), Data = null, Message = arr };
actionContext.Response = new HttpResponseMessage {
                Content = new StringContent(JsonConvert.SerializeObject(output), Encoding.UTF8, "application/json"),
                StatusCode = HttpStatusCode.OK
            };