Posting to ASP.NET 5 WebAPI Controller from Aurelia

A small post for my own reference, and yours if you need it.

It took me a while to get this working. In ASP.NET 5, the WebAPI Controller is no longer the same as the WebAPI 2 Controllers we're used to.

These Controllers are quite specific on how they accept content. Aurelia has an easy way of posting to a Controller:

import {HttpClient} from 'aurelia-http-client'

@inject(HttpClient)
export class MyViewModel {
    constructor(http) {
        this.http = http;
    }

    callService() {
        this.http.post('http://some/url', { value: 'test' });
    }
}

In the Controller, you might have something like:

[HttpPost]
public string Post([FromBody]MyDTO myDto)
{
    var value = myDto.value;
    //....
}

However, this won't work. Aurelia will post this as text/plain, whereas our Controller expects JSON.

The solution is the more verbose way of constructing a request in Aurelia:

this.http.createRequest('http://some/url')
         .asPost()
         .withHeader('Content-Type', 'application/json; charset=utf-8')
         .withContent({ value: 'test' })
         .send()
         .then(response => {
             console.log(response.response);
         }).catch(err => {
             console.log(err);
         });

Problem solved! ASP.NET will map your JSON to the .NET class (myDTO in the example above).