Support $format in ASP.NET Web Api

OData protocal defines $format to support different format: https://www.odata.org/documentation/uri-conventions\#FormatSystemQueryOption

User can use following URL to change the return format to json instead of setting Accept header: https://localhost/api/Values?$format=json

However, QueryableAttribute in Web Api OData package doesn't support $format.

ASP.NET Web Api provides such extensibility that you can change the default content negotiation by adding mappings to any part of the a request. So what we just need to do is to add following code to WebApiConfig.cs:

  1: public static class WebApiConfig 
  2: { 
  3:     public static void Register(HttpConfiguration config) 
  4:     { 
  5:         config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json"); 
  6:         config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); 
  7:         config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", 
  8:             defaults: new { id = RouteParameter.Optional } ); 
  9:     } 
  10: } 

In order to support QueryableAttribute together with $format, you also need to extend it to make it silent on unsupported query options. Following code do the trick:

  1: public class ExtendedQueryableAttribute : QueryableAttribute 
  2: { 
  3:     public override void ValidateQuery(System.Net.Http.HttpRequestMessage request) 
  4:     { // don't report error for unsupported query 
  5:     } 
  6: } 

BTW, at current point, the ValidateQuery method is not virtual in public nuget pacakge. You can use it nighly build feed to install the nightly build: https://www.myget.org/F/aspnetwebstacknightly/

Download Sample Code