5 Days of Simple.Web: Content Negotiation

Content negotiation

I’ve mentioned one of the key ingredients of a ReST API is “representation”. It is likely the representation sent back to the client is an abstract of the actual resource exposed. Furthermore the content of the representation will need to be encoded and in a format the client can consume, it will need to be negotiated.

Negotiate

Fortunately HTTP/1.1 provides us with headers to enable the negotiation between client and server.

Request

123

GET /customers HTTP/1.1
Accept: text/html
Accept-Charset: utf-8

When receiving a request Simple.Web will invoke the appropriate media-type handler for that requested.

Handle

Simple.Web supports content negotiation using available media-type handlers. The following media-type handlers are available as NuGet packages;

Respond

If no matching handler is available Simple.Web will respond 415 Unsupported media type.

Razor

Simple.Web.Razor allows association of a view with a model, a handler, or both. Properties of any associated model or handler are exposed to the view, avoiding the need for an ambiguous view-bag. Should you wish to share data between layouts and sections without polluting your model or handler then ViewBag is available.

[GET] GetEndpoint.cs

123456789101112131415161718192021222324252627282930

namespaceContentNegotiation.Customers{usingSystem;usingSimple.Web;usingSimple.Web.Behaviors; [UriTemplate("/customers")]publicclassGetEndpoint:IGet,IOutput<IEnumerable<CustomersModel>>{privateICustomersQuerycustomerQuery;publicGetEndpoint(ICustomersQuerycustomersQuery){this.queryCustomers=queryCustomers;}publicstringTitle{get;set;}publicIEnumerable<CustomersModel>Customers{get;set;}publicStatusGet(){this.Title="Customer list as of "+DateTime.Now.ToLongDateString();this.Customers=this.customersQuery.Execute();return200;}}}

Discovery

I mentioned above that media-type handlers were “discovered” at runtime; to be exact they are imported from the AppDomain. To ensure the Type’s of media-type handlers in referenced assemblies are included I recommend a code reference that CodeAnalysis won’t think better for you.

You can do this using an IoC container (of which Simple.Web supports Autofac, Ninject, and StructureMap) to scan the appropriate assemblies, alternatively reference the assemblies at compile-time. For example;