title: ASP.NET MVC: How to create an action filter to output JSON?
body: <p>My second day with ASP.NET MVC and my first request for code on SO (yep, taking a short cut).</p>
  
  <p>I am looking for a way to create a filter that intercepts the current output from an Action and instead outputs JSON (I know of <a href="http://weblogs.asp.net/omarzabir/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx" rel="nofollow noreferrer">alternate approaches</a> but this is to help me understand filters). I want to ignore any views associated with the action and just grab the ViewData["Output"], convert it to JSON and send it out the client. Blanks to fill:</p>
  
  <p><code>TestController.cs:</code></p>
  
  <pre><code>[JSON]
  public ActionResult Index()
  {
      ViewData["Output"] = "This is my output";
      return View();
  }
  </code></pre>
  
  <p><code>JSONFilter.cs:</code></p>
  
  <pre><code>public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     /*
      * 1. How to override the View template and set it to null?
      * ViewResult { ViewName = "" } does not skip the view (/Test/Index)
      * 
      * 2. Get existing ViewData, convert to JSON and return with appropriate
      * custom headers
      */
  }
  </code></pre>
  
  <p>Update: Community answers led to a fuller implementation for a <a href="http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/" rel="nofollow noreferrer">filter for JSON/POX</a>.</p>