Add Web API to your .NET Core application

October 6, 2016 · 4 minute read

tl;dr Web API and MVC have been combined in .NET Core and attribute routing makes it dead easy to quickly build your API.

If you’ve been following along as we’ve created a basic .NET Core web application from scratch then you might have wondered when we’ll get to Web API.

As it happens, we already added support for it when we set up MVC.

In ASP.NET Core, MVC and Web API have been combined.

What’s changed exactly?

Previously you had to inherit from different controller base type depending on whether you wanted an API or MVC controller.

If you wanted to return data instead of views you had to inherit from ApiController.

Action Filters used to have separate implementations/pipelines. This meant you could happily apply an Action Filter to a controller only to find it didn’t actually do anything because it was written for Web API not MVC.

Now in .NET Core the same base Controller types and ActionFilters support both API and MVC.

Here’s a simple example of a controller with API methods (that return data).

Create this in your controllers folder.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace CoreNotes
{
    [Route("api/[controller]")]
    public class NoteController : Controller
    {
        [HttpGet("")]
        public IEnumerable<Note> List(string username)
        {
            return new List<Note>{
                new Note{Title = "Shopping list", Contents="Some Apples"},
                new Note{Title = "Thoughts on .NET Core", Contents="To follow..."}
             };
        }
    }
}

Create the following class (I put it in a folder called Models but the location isn’t important).

namespace CoreNotes
{
    public class Note
    {
        public string Title { get; set; }
        public string Contents { get; set; }
    }
}

Now run your app and navigate to /api/note you’ll see a list of extremely exciting notes…

simple-list-api

It’s all in the routing

If you ever wrestled with routing in previous versions of MVC you’ll no doubt have some horror stories to tell about when it all went wrong and you had no idea why.

Attribute routing makes it possible to configure your application’s routing using attributes applied directly to your controller and its actions.

You can start by defining a “catch-all” route prefix to your controller class which will apply to all of the actions.

[Route("api/[controller]")]

This means every action on this controller will be accessed starting with http://yourapp/api/note.

A neat trick is that you don’t even need to type out the controller’s name as [controller] will work that out for you (just be careful, if you subsequently rename the controller the url will change too).

We’re sticking to REST conventions here by returning a list when the API is called without any additional instructions e.g. /api/note

To do this you just need to specify the HTTP Verb and leave the route template argument empty.

[HttpGet("")]

There can be only one

And if you want to get the details of a specific note?

You can specify parameters in the route template.

Let’s use a url like this http://yourapp/api/note/1 (returns the note with id 1).

using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;

namespace CoreNotes
{
    [Route("api/[controller]")]
    public class NoteController : Controller
    {
        [HttpGet("")]
        public IEnumerable<Note> List(string username)
        {
            return new List<Note>{
                new Note{Title = "Shopping list", Contents="Some Apples"},
                new Note{Title = "Thoughts on .NET Core", Contents="To follow..."}
             };
        }

        [HttpGet("{id}")]
        public Note Details(int id)
        {
            return new Note{Title = "one note", Contents = $"here's a note whose id is... {id}"};
        }
    }
}

We’re sticking with hard coded data for now but in reality you’d probably wire this up to your database and pass the id in the query.

Test it out in the browser.

single-note

In Summary

There’s a lot more you can do with Web API and routing but getting started is easy.

Once you’ve got the basics down you can start looking at more advanced routing and hooking up an ORM (e.g. Entity Framework) to serve your application’s data.

photo credit: Duke of Medway Switchboard job via photopin (license)

Join the Practical ASP.NET Newsletter

Ship better Blazor apps, faster. One practical tip every Tuesday.

I respect your email privacy. Unsubscribe with one click.