How to integrate ASP.NET WebApi AttributeRouting with HyprLinkr

Today I would like to show you how to use HyprLinkr with AttributeRouting. HyprLinkr works with the standard route configuration created by the Visual Studio project template (route named "API Default"). If you would like to make it work with another routing framework you have to tweak somehow HyprLinkr. Hopefully, the API is very developer-friendly and Mark Seemann which is the creator of HyprLinkr has provided some means for doing it very easily. For those who don't know AttributeRouting, it allows to define route templates in attributes directly on the controllers and actions. It allows some extra features like hierarchical route definition and so on.

Tweaking of HyprLinkr

If you recall from my previous post StructureMap is configured to inject IResourceLinker in order to resolve url for hypermedia links. However with AttributeRouting it won't work. For that we need to implement our own IRouteDispatcher interface and to provide the implementation to the IResourceLinker instance being resolved by StructureMap. Here's the implementation of IRouteDispatcher for AttributeRouting framework :

We need to return a Rouple object with a routeName and route values in order to allow HyprLinkr to generate the right url. As input we only need an instance of HttpRequestMessage. This is necessary to access the configured routes in the RouteTable. When the application is being run for the first time, the AttributeRouting framework scans all the controllers and extracts url templates from the attributes. Then it adds these to the Route table of WebApi configuration object. We need to match the template url extracted from the controller action attribute to the route configured in the route table and then get its name to construct our Rouple object. In order to match an url to the attribute's template we have to apply a regex that strips some special characters from the template (type definitions like ":int?", optional parameter "?", etc.)

Configuring all

In order to construct our rouple object in the custom dispatcher, we need to tell to AttributeRouting framework to generate route names for each registered route (by default this is not done and we can't use it with HyprLinkr). The configuration can be done in WebApi registration section. AutoGenerateRouteNames should be set to true :

In closing

As you noticed, it's very straightforward to adapt HyprLinkr to work with other routes definition frameworks in WebApi. AttribouteRouting will be the next important feature of WebApi Next (V2) so it's important to know how to make it work with HyprLinkr if you're using it as your hypermedia links generating framework.

Welcome to my blog! F# and functional programming it's what I'm interested in and passionate about at the moment. However, software architecture, software craftsmanship, Domain Driven Design are also topics dear to my heart. So stay tuned! There is more to come...