• Stars
    star
    212
  • Rank 184,989 (Top 4 %)
  • Language
    C#
  • License
    Microsoft Public ...
  • Created about 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

Adds support for the Hal Media Type (and Hypermedia) to Asp.net Web Api

WebApi.Hal

Adds support for the Hal Media Type (and Hypermedia) to Asp.net Web Api

HAL Specification

http://stateless.co/hal_specification.html
https://github.com/mikekelly/hal_specification

Getting Started with WebApi.Hal

First thing first, WebApi.Hal is a media formatter. So to get started you have to register the Hal Media formatters:

GlobalConfiguration.Configuration.Formatters.Add(new JsonHalMediaTypeFormatter());
GlobalConfiguration.Configuration.Formatters.Add(new XmlHalMediaTypeFormatter());

Once those are registered, you can start defining your resources. In WebAPI.Hal, you always return Representations from your ApiControllers.

Your representations should all inherit from Representation or if you are returning a collection a SimpleListRepresentation<TRepresentation> or if you are returning a resource with multiple embedded resources, inherit from Representation and add properties for the embedded resources which might include lists of resources of the form List<MyRepresentation>. See the sample.

WebApi.Hal.Link

The link class represents hypermedia on a representation. It looks like this:

public class Link
{
	public string Rel { get; set; }
	public string Href { get; set; }
	public string Title { get; set; }
	public bool IsTemplated { get; set; }
	public Link CreateLink(...);
}

The thing which makes this class special is it's support for templates. For example:

var link = new Link("beers", "/breweries/{id}/beers");

Notice the {id}, this allows you to return a templated link as hypermedia. But you can also turn it into an absolute link really easily:

Brewery brewery;
link.CreateLink(new { id = brewery.Id });

URI Templates adhere to RFC6570, as per the HAL specification.

Register WebAPI routes

Once you have done the work of defining all your link templates, register your routes in the ordinary MVC WebApi manner. See the sample project for an example.

LinkTemplates class

A nice place to keep your Links is in a static class called LinkTemplates, with nested classes for each resource your application has, for example:

public static class LinkTemplates {
	public static class Beers {
		/// <summary>
		/// /beers/{id}
		public static Link Beer { get { return new Link("beer", "/beers/{id}"); } }

		/// <summary>
        /// /beers?page={page}
        /// </summary>
        public static Link GetBeers { get { return new Link("beers", "/beers{?page}"); } }
	}
}

The sample is available at: https://github.com/JakeGinnivan/WebApi.Hal/blob/master/WebApi.Hal.Web/LinkTemplates.cs

WebApi.Hal.Representation

This is the base class for all representations your api returns. It has an abstract method you must override, abstract void CreateHypermedia();

In the constructor, set the Rel property, as this generally doesn't change based on context.

In CreateHypermedia() you could register a self link, but it's done automatically for you if you don't. Register other hypermedia that your resource should always have. Other context sensitive hypermedia should be added in the API controller.

Here is an example of the Beer CreateHypermedia override (from the example project, the BeerResource):

public Beer()
{
	Rel = LinkTemplates.Beers.Beer.Rel;
}
protected override void CreateHypermedia()
{
	Href = LinkTemplates.Beers.Beer.CreateLink(new { id = Id }).Href;

	if (StyleId != null)
		Links.Add(LinkTemplates.BeerStyles.Style.CreateLink(new { id = StyleId }));
	if (BreweryId != null)
		Links.Add(LinkTemplates.Breweries.Brewery.CreateLink(new { id = BreweryId }));
}

Sample controller action

public BreweryRepresentation Get(int id)
{
	var brewery = beerDbContext.Breweries.Find(id);

	return new BreweryRepresentation
	{
		Id = brewery.Id,
		Name = brewery.Name,
		Links =
		{
			LinkTemplates.Breweries.AssociatedBeers.CreateLink(new { id })
		}
	};
}

Sample Project

To run the sample project, update the connection string in web.config, then create the database. When you hit an API for the first time, the database will be setup using DbUp.

You can use fiddler to explore the API. Make sure you put in an accept header of application/hal+json. Try hitting http://localhost:51665/beers with that accept header, and see what happens

Credits

I have more credits to add, but this is the most obvious (as I based my Xml formatter off this project)

https://bitbucket.org/smichelotti/hal-media-type

Release Notes

See Readme.txt at http://github.com/JakeGinnivan/WebApi.Hal

More Repositories

1

react-popout

React popout is a React component wrapping window.open allowing you to host content in a browser popup window.
JavaScript
188
star
2

VSTOContrib

VSTO Contrib lets you easily unit test, use IoC/DI and develop in a MVVM style within Office Add-ins. It supports Outlook, Word, Excel and PowerPoint 2007 or 2010, and has both .net 3.5 and 4.0 builds
C#
130
star
3

react-redux-notifications

Redux powered notification React components.
TypeScript
113
star
4

SettingsProvider.net

Simple Settings provider for .net applications
C#
59
star
5

ExpressionToString

Expression.ToString() is not so nice to look at sometimes, this library will ToString your expression in the way you want
C#
26
star
6

GitHubFlowVersion

The easy way to use semantic versioning (semver.org) with GitHub Flow
C#
18
star
7

WebPack-React-Starter

Understanding starter repos is sometimes hard, this repo will show you how we got there. Commit by commit
18
star
8

VSTest.TeamCityLogger

Enables TeamCity to display output when tests are run through VSTest.console.exe
C#
9
star
9

Drone

Drone gives you a birdseye view of all your OSS projects to help you see what to do next. It may even do some of it for you down the track!
JavaScript
9
star
10

TfsBuildResultPublisher

Based off http://blogs.msdn.com/b/jpricket/archive/2010/02/23/creating-fake-builds-in-tfs-build-2010.aspx and http://msmvps.com/blogs/vstsblog/archive/2011/04/26/creating-fake-builds-in-tfs-build-2010-using-the-command-line.aspx
C#
8
star
11

spectacle-typescript-boilerplate

Boilerplate for https://github.com/FormidableLabs/spectacle using TypeScript
TypeScript
8
star
12

XamlAttributeOrderingCodeCleanup

ReSharper Plugin which orders Xaml Attributes
C#
7
star
13

ndc-sydney-pulumi-demo

TypeScript
6
star
14

XText

Allows you to create nicely formatted WPF text from code behind with a syntax similar to the way XDocuments work
C#
6
star
15

SqlConnectionControl

Code for http://jake.ginnivan.net/wpf-sql-connection-user-control
C#
6
star
16

UITextBlock

Wpf TextBlock that supports UI Automation and some other nice things
C#
4
star
17

urban-plate

JavaScript
4
star
18

gru

Gru is a node clustering helper, because he is the leader of the minions
TypeScript
4
star
19

practical-typescript

TypeScript
4
star
20

AsyncAutomapper

C#
3
star
21

TestCaseAutomationAssigner

Allows you to assign non-mstest tests to Test Cases in TFS
C#
3
star
22

AsyncAllTheThings

JavaScript
2
star
23

DelegateInvoker

Invoke methods via reflection without wrapping errors in a TargetInvocationException
C#
2
star
24

jakeginnivan.github.io

My Blog
JavaScript
2
star
25

wee-dram

JavaScript
2
star
26

example-project-structure

Example of how I setup my NPM projects
JavaScript
2
star
27

merge-refs-hook

This package makes it easy to have a component which requires a ref but also wants to support forwarding refs
TypeScript
2
star
28

modern-typescript-is-awesome-demos

1
star
29

advent-of-code

JavaScript
1
star
30

vite-ssr-build-issue

TypeScript
1
star
31

getting-more-out-of-typescript

TypeScript
1
star
32

IsThatEvenJS

JavaScript
1
star
33

dotfiles

Shell
1
star
34

node-git-release-notes

TypeScript
1
star
35

es6-samples

TypeScript
1
star
36

pulumi-fargate-task

TypeScript
1
star
37

pulumi-locked

Pulumi CLI wrapper which supports taking locks in DynamoDB.
JavaScript
1
star
38

ArgyBargy

A simple clean API for showing flexible WPF dialogs
C#
1
star
39

react-json-pages

Create your layouts and components then compose them with JSON. Opens up opportunities to CMS manage your React pages and cut down on boilerplate across pages. Useful if you are building websites with React rather than applications
1
star