Web API Extensibility

jon-flanders-v1Welcome to this review of the final module from Jon Flanders’ course Introduction to the ASP.NET Web API

Jon has helped numerous companies create and transform mobile teams into teams that can create, build, test, and deploy mobile applications with ease.

Jon is excited for the next phase of mobile development and exploring how technology can not only entertain us, but help create a connected world where smart devices start to perform tasks that are difficult and time-consuming.

The full course also the following modules for you to enjoy:

  • Introduction
  • Uniform Interface
  • HttpClient
  • Hosting
  • Security

Extensibility

Getting Started

The path to Web API extensibility is through the HttpConfiguration object.

The ASP.NET hosting extensions, we need to use the GlobalConfiguration.Configuration property.
Typically, we change this in global.asax.cs.

If we are self-hosting, we create our own instance of HttpConfiguration directly.

Jon discusses some of the miscellaneous properties:

IncludeErrorDetailPolicy – similar to the Web.config custom errors element, but for Web API

There are three possible settings:

– LocalOnly (default) – exception detail is only shown to requests from localhost
– Always
– Never

Properties
Property bag that can be used to store per instance data

Formatters

When we want to extend Web API to handle media types that aren’t built in.

The WebApiContrib project has created many useful additional Formatters, so I highly recommend looking there first rather than reinventing the wheel.
Also if you create a new formatter that is not included in WebApiContrib, consider submitting your work to the project so that everyone else can benefit.

Formatters are classes that derive from MediaTypeFormatter
They perform serialization and deserialization
They are based on Media Types (HTTP Content-Type header)

Once a new formatter is added to the HttpConfiguration.Formatters collection, we have a new type of Content-Type that we can handle.

Demo – Formatters

Jon creates a JSONP Demo. JSONP is a way to interject JavaScript into a page loaded from a different domain
See the Security module of Shawn Wildermuth’s course for further details on JSONP as well as Cross Origin Resource Sharing.

Our new Controller has a Get method that takes an integer id and a string callback.
It returns a HttpResponseMessage that has a JSONPReturn object content and “application/javascript” content type.

Our JSONPReturn type contains Callback and JSON string properties.

We also create a new class MyJSONPFormatter which derives from MediaTypeFormatter, and overrides the following MediaTypeFormatter methods:

– CanWriteType
– CanReadType
– WriteToStreamAsync

The advantage of splitting out the code like this is we can later create more types and have the formatter deal with all of them.

To test this, Jon writes an HTML file with a couple of script blocks.
One script block with a myCallBack function which sets text on a h1 element
The another script block calls the api service and sets the callback to our new JavaScript function:

http://localhost:3403/api/jsonp?id=42&callback=myCallBack

When we run the HTML file in our browser, we see the message “Hello from JSONP Web API Style” proving that our Formatter is working

By looking at the dev tools, we also see this message is returned in the Response body.

Filters

Filters allow us to pre and post process requests before they go into a controller method.

Filters hook into the model binding and controller execution pipeline.

Any generic process that we want to do across many requests, may be best implemented as a Filter.

All filters implement the IFilter interface.

Message Handlers

We can also modify the actual processing pipeline using Message Handlers.

To implement a message handler we derive from DelegatingHandler

Demo – Message Handlers

Jon creates an XMethodOverride project which aims to create a uniform interface that’s based on GET, POST, PUT and DELETE.

Some HttpClients have limited access to certain verbs, e.g. many can only do GET and POST and are forbidden from doing PUT and DELETE.
One example of this is Adobe Flash but there are several others as well.

One technique for getting around this limitation is to add an extra header called X-HTTP-Method-Override.
This gives the server the additional information needed to determine that although it is, for example, a POST request, the header explains that the client actually wants to make a PUT request.

This is what we implement here, starting with Global.asax.cs, where we add our new MyMethodOverrideHandler to the MessageHandler Collection.

Of course we must write our MyMethodOverrideHandler. It derives from DelegatingHandler and has the constant “X-HTTP-Method-Override”

This implementation only works for overriding the Post method, but this pattern could easily be extended to override GET methods as well if required.

Jon shows this working using Fiddler. It ends up calling the Put method instead of the Post method.

Action Filter vs Message Handlers

When we want to build something additional, should we create a new Filters or a new Message Handler?

We need to think about the processing pipeline and where we need to make our changes.

MessageHandler lives before model binding and is more at the HTTP message level.

Action Filters execute after model binding, and are more geared towards doing operations after the method to invoke has been selected.

However, Jon says we can implement the same functionality in both much of the time and it is just a design choice based on our preferences.

Writing Action Filters often, but not always, involve a bit less code than writing a new MessageHandler.
Jon says the choice have more to so with pragmatism than technology.

ServiceResolver

This is a short clip that merely introduces this concept:

Web API was designed to be very easy to unit test and ServiceResolver plays a role in this.

This is a pattern to find services and is a form of dependency injection.

We can add our own IoC container, implement IDependency Resolver and set the DependencyResolver property on the appropriate HttpConfiguration.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s