• Stars
    star
    197
  • Rank 191,474 (Top 4 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 12 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A URI building helper library for ASP.NET Web API

Hyprlinkr

Hyprlinkr is a small and very focused helper library for the ASP.NET Web API. It does one thing only: it creates URIs according to the application's route configuration in a type-safe manner.

As of version 2 it works with ASP.NET Web 2. Look for version 1 for compatibility with ASP.NET Web API 1.

Example

Imagine that you're using the standard route configuration created by the Visual Studio project template:

name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }

In that case, you can create an URI to a the resource handled by the FooController.GetById Action Method like this:

var uri = linker.GetUri<FooController>(r => r.GetById(1337));

This will create a URI like this:

http://localhost/api/foo/1337

assuming that the current host is http://localhost. Creating a RouteLinker instance

The RouteLinker class has two constructor overloads:

public RouteLinker(HttpRequestMessage request)

public RouteLinker(HttpRequestMessage request, IRouteDispatcher dispatcher)

In both cases it requires an instance of the HttpRequestMessage class, which is provided by the ASP.NET Web API for each request. The preferred way to get this instance is to implement a custom IHttpControllerActivator and create the RouteLinker instance from there.

public IHttpController Create(
    HttpRequestMessage request,
    HttpControllerDescriptor controllerDescriptor,
    Type controllerType)
{
    var linker = new RouteLinker(request);

    // Use linker and other services to create the appropriate Controller.
    // If desired, a DI Container can be used for this task.
}

Such a custom IHttpControllerActivator can be registered in Global.asax like this:

GlobalConfiguration.Configuration.Services.Replace(
    typeof(IHttpControllerActivator),
    new MyCustomControllerActivator());

This approach enables the use of Dependency Injection (DI) because the request can be injected into the services which require it.

Without Dependency Injection

As an alternative to Dependency Injection (DI), the request can also be pulled directly from the ApiController instance. This requires that Controllers derive from ApiController. If this is the case, a RouteLinker instance can be created easily:

var linker = new RouteLinker(this.Request);

The example code includes a NoDIController class that demonstrates this approach.

From an API Controller

If you want to use Hyprlinkr directly from an ApiController, you can use extension methods to create links:

// Inside an ApiController
var uri = this.Url.GetLink<FooController>(a => a.GetById(1337));

This will create a URI like this:

http://localhost/api/foo/1337

assuming that the current host is http://localhost. Custom route dispatching

The default behavior for RouteLinker is:

  • If the method being linked to has a [Route] attribute with a route name defined, use that route. Note that you cannot link to a method with an unnamed [Route] attribute
  • Otherwise assume that there's only a single configured route, and that route is named "API Default"

This behavior is implemented by the DefaultRouteDispatcher class. If you require different dispatching behavior, you can implement a custom IRouteDispatcher and inject it into the RouteLinker instances. Nuget

Hyprlinkr is available via nuget Versioning

Hyprlinkr follows Semantic Versioning 2.0.0. Example code

The ExampleService project, included in the source code, provides a very simple example of how to wire and use Hyprlinkr. As an example, in HomeController.cs you can see that links are added to a model instance like this:

public HomeModel Get(string id)
{
    return new HomeModel
    {
        Name = id,
        Links = new[]
        {
            new AtomLinkModel
            {
                Href = this.linker.GetUri<HomeController>(r =>
                    r.Get(id)).ToString(),
                Rel = "self"
            },
            new AtomLinkModel
            {
                Href = this.linker.GetUri<HomeController>(r =>
                    r.Get()).ToString(),
                Rel = "http://sample.ploeh.dk/rels/home"
            }
        }
    };
}

This produces a representation equivalent to this:

<home xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      xmlns="http://www.ploeh.dk/hyprlinkr/sample/2012">
    <links>
        <link xmlns="http://www.w3.org/2005/Atom"
              href="http://localhost:6788/home/ploeh"
              rel="self"/>
        <link xmlns="http://www.w3.org/2005/Atom"
              href="http://localhost:6788/"
              rel="http://sample.ploeh.dk/rels/home"/>
    </links>
    <name>ploeh</name>
</home>

In order to run the sample application, open the Hyprlinkr.sln solution and set ExampleService as the startup project, then run the application by hitting F5 (or Ctrl+F5). Credits

The strongly typed Resource Linker idea was originally presented by Josรฉ F. Romaniello.

More Repositories

1

ZeroToNine

A tool for maintaining .NET Assembly versions across multiple files.
F#
145
star
2

Booking

Demo code demonstrating how to manage a complex code base with DI, Convention over Configuration, etc.
JavaScript
126
star
3

ploeh.github.com

ploeh blog 'source code'
HTML
118
star
4

Furl

Interact with HTTP resources using F# scripting
F#
76
star
5

Numsense

A .NET library for parsing natural-language numerals ("forty-two") to integers, and converting the other way as well
F#
62
star
6

asynchronous-injection

Sample code accompanying blog article
C#
44
star
7

CQRSonAzureDemo

Demo code accompanying the CQRS on Azure MSDN Magazine article
JavaScript
30
star
8

KataTennis

Supporting code for an article series called "Types + Properties = Software"
F#
29
star
9

UserManagement

Sample code for Humane Code episodes
C#
26
star
10

booking-web-ui

AngularJS-based UI for my Pluralsight course on Functional Architecture with F#
JavaScript
23
star
11

dependency-rejection-samples

Supporting code for an article series called From dependency injection to dependency rejection
HTML
23
star
12

advent-of-code-2017

Solutions for Advent of Code 2017
Haskell
15
star
13

ChurchEncoding

Examples of Church encodings in C#
C#
15
star
14

dependency-injection-revisited

Sample code for articles
C#
14
star
15

ExtensibilityForMasses

C#
12
star
16

BookingExercise

Start code for refactoring exercises
C#
11
star
17

RunningJournalApi

The code in this repository is sample/demo code used for Mark Seemann's presentation "REST with the ASP.NET Web API"
C#
10
star
18

loan

This is sample code accompanying my presentation "Faking Homoiconicity in C# with graphs".
C#
10
star
19

reservation-api-slice-csharp

C# demo code of a full vertical slice from HTTP to database
C#
7
star
20

DiamondFsCheck

The Diamond kata done with Property-Based Testing in F#
F#
5
star
21

PureInteractionsInFSharp

Example code accompanying http://blog.ploeh.dk/2017/07/31/combining-free-monads-in-f
HTML
5
star
22

StatePatternAndMonad

Sample code supporting a blog post about the State pattern and the State monad
C#
5
star
23

PureInteractionsInHaskell

Example code accompanying http://blog.ploeh.dk/2017/07/24/combining-free-monads-in-haskell
Haskell
5
star
24

picture-archivist

Example code supporting blog articles
F#
5
star
25

PollingConsumer

A pure Polling Consumer written in F#
HTML
4
star
26

UserProfile

Code examples for https://blog.ploeh.dk/2019/07/22/chain-of-responsibility-as-catamorphisms
PowerShell
4
star
27

EquivalenceClassesFsCheckFizzBuzz

Code from my Equivalence Classes, xUnit.net, FsCheck, Property-Based Testing presentation.
F#
4
star
28

Hull

Graham Scan implementation in F#
F#
4
star
29

TCPStateCSharp

State pattern TCP example in C#
C#
3
star
30

ChurchEncodingCore

.NET Core port of ChurchEncoding repository
C#
3
star
31

HasProblem23

Haskell problem 23
Haskell
3
star
32

restaurant-reservation-exercises

Exercises for programming workshop
C#
3
star
33

RegistrationFlow

Example code for article
F#
3
star
34

ArgsCSharp

Code repository supporting a blog post
C#
2
star
35

maitred-kata-in-fsharp-1

The Maรฎtre d' kata done in F#
F#
2
star
36

BrainfuckCSharp

Code repository supporting a blog post
C#
2
star
37

UserManagementCore

.NET Core port of UserManagement repository
C#
2
star
38

reservation-api-slice-haskell

Haskell demo code of a full vertical slice from HTTP to database
Haskell
2
star
39

RangeHaskell

A Haskell implementation of the Range kata
Haskell
2
star
40

FAlgebras

Various F-Algebras implemented in Haskell; supports article series.
Haskell
1
star