title: Wrapping results of ASP.NET Core WebAPI methods using IResultFilter
body: <p>I have implemented a result filter like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class ResultWrapperFilter : IResultFilter
  {
      public void OnResultExecuting(ResultExecutingContext context)
      {
          if (!(context.ActionDescriptor is ControllerActionDescriptor))
          {
              return;
          }
  
          var objectResult = context.Result as ObjectResult;
          if (objectResult == null)
          {
              return;
          }
  
          if (!(objectResult.Value is WrappedResponseBase))
          {
              objectResult.Value = new WrappedResponse(objectResult.Value);
          }
      }
  
      public void OnResultExecuted(ResultExecutedContext context)
      {
      }
  }
  </code></pre>
  <p>The filter is used by configuring <code>MvcOptions</code> through <code>ConfigureServices(IServiceCollection services)</code> like this:</p>
  <pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
  {
      services.Configure&lt;MvcOptions&gt;(
              options =&gt; { options.Filters.AddService&lt;ResultWrapperFilter&gt;(); });
      services.AddMvc();
  
      // ... the rest is omitted for readability
  }
  </code></pre>
  <p>The problem I'm experiencing is this filter is causing <code>InvalidCastException</code>: Unable to cast object of type 'WrappedResponse' to type 'System.String' (the method in question has string as the return value type).</p>
  <p>Am I even allowed to do this using IResultFilter?</p>
  <p><strong>NOTE:</strong> I am aware of the possibility of using middleware to accomplish the response wrapping. I don't want to use the middleware to accomplish this because the middleware doesn't have access to <code>context.Result as ObjectResult</code>. Deserializing from the response stream, wrapping and serializing again seems so unnecessary.</p>