Doc/Codecs/MediaTypeAttribute

The MediaType attribute

The MediaType attribute allows you to specify good defaults for a codec. Without this attribute, your fluent config would be cluttered by repeated lines of this sort:

    // ... some resource definition and handler definition here ... //
         .TranscodedBy<JsonDataContractCodec>(null).ForMediaType("application/json").ForExtension(".json")

Instead, the JsonDataContractCodec has this MediaType attribute associated with it:

[MediaType("application/json;q=0.5", "json")]

The first parameter is the media type itself, which is split into two parts by a semicolon (;):

  • The internet media type (in this case, application/json)
  • The quality rating, as a floating point number. A number closer to 1.0 is a higher rating, whereas a number closer to 0.0 is a lower rating. Where a client has stated that more than one representation is acceptable, the higher quality representation will be rendered, if available. If a client has provided a quality of 0 for a media type, this means the client does not want to receive that type under any circumstance.

The presence of this attribute means that one can shorten every instance of our previous verbose configuration to

    // ... some resource definition and handler definition here ... //
         .TranscodedBy<JsonDataContractCodec>(null);

... although in practice we'd use the (even shorter) shorthand extension:

    // ... some resource definition and handler definition here ... //
         .AsJsonDataContract();