title: ASP.NET Core ways to handle custom response/output format in Web API
body: <p>I'd like to create custom JSON format, that would wrap the response in data and would return Content-Type like </p>
  
  <blockquote>
    <p>vnd.myapi+json</p>
  </blockquote>
  
  <p>Currently I have created like a wrapper classes that I return in my controllers but it would be nicer if that could be handled under the hood:</p>
  
  <pre><code>public class ApiResult&lt;TValue&gt;
  {
      [JsonProperty("data")]
      public TValue Value { get; set; }
  
      [JsonExtensionData]
      public Dictionary&lt;string, object&gt; Metadata { get; } = new Dictionary&lt;string, object&gt;();
  
      public ApiResult(TValue value)
      {
          Value = value;
      }
  }
  
  [HttpGet("{id}")]
  public async Task&lt;ActionResult&lt;ApiResult&lt;Bike&gt;&gt;&gt; GetByIdAsync(int id)
  {
      var bike = _dbContext.Bikes.AsNoTracking().SingleOrDefault(e =&gt; e.Id == id);
      if (bike == null)
      {
          return NotFound();
      }
      return new ApiResult(bike);
  }
  
  public static class ApiResultExtensions
  {
      public static ApiResult&lt;T&gt; AddMetadata&lt;T&gt;(this ApiResult&lt;T&gt; result, string key, object value)
      {
          result.Metadata[key] = value;
          return result;
      }
  }
  </code></pre>
  
  <p>I'd like to return response like:</p>
  
  <pre><code>{
      "data": { ... },
      "pagination": { ... },
      "someothermetadata": { ... }
  }
  </code></pre>
  
  <p>But the pagination would have to be added somehow to the metadata in my controller's action, of course there's some article about content negotiation here: <a href="https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1" rel="noreferrer">https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1</a> but still I'd like to be sure I'm on the right track.</p>
  
  <p>If that would be handled under the hood with my custom formatter then how would I add metadata like a pagination to it, to be aside of "data" and not inside of it?</p>
  
  <p>When having a custom formatter I'd like to still have some way to add metadata to it from my controllers or by some mechanism so the format could be extensible.</p>
  
  <p>One advantage or disadvantage with the approach above is that it works with all serializers xml, json, yaml etc. By having custom formatter it would probably work only for json, and I will need to create few different formatters to support all the formats that I want.</p>