Skip to content

Instantly share code, notes, and snippets.

@cilliemalan
Last active September 9, 2016 14:55
Show Gist options
  • Save cilliemalan/6057dd45bb2e897445d29cf115b99c50 to your computer and use it in GitHub Desktop.
Save cilliemalan/6057dd45bb2e897445d29cf115b99c50 to your computer and use it in GitHub Desktop.
Creating ASP.Net Web API /w C# client

How to make an API Server

Step 1: New Project

Go to File -> New Project And create a Web Project:

img

Select Web API

img

It will create a solution with some files.

img

Run it and make sure it works!

img

img

Yay it works! Now lets go to the values controller

img

and disasble auth for now. Remove the [Authorize] line

img

Now run the project again and naviage to http://localhost:port/api/values.

img

Yay it works!

BUT it's XML and that's stupid. It will decide what to send back depending on the Accept header of the request but for our own sanity let's disable XML. Open the file App_Start/WebAPiConfig.cs

img

Go to this line:

img

And add this code:

//remove XML Formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);

Now run and go the the same URL:

img

Excellent! Now let's move on to

Step 2 Database Migrations

The API already has a database built in, but we'll likely want some extra features. So let's make the database auto-migrate on startup.

Open the Package Manager Console. A quick way to do this is to press Ctrl+Q and start typing "Package Manager Console" img

And here we go: img

Now make sure the default project is correct (right now there is just one so okay): img

And type in the box:

Enable-Migrations

VS will churn for a while and add a bunch of files. The new Configuration.cs file will be opened. Save and build to make sure everything checks out. Next, we're going to make sure the database migrates whenever it is used.

Open Models/IdentityModel.cs and look at ApplicationDbContext. Add this static constructor at the top of the class:

static ApplicationDbContext()
{
    var initializer = new System.Data.Entity.MigrateDatabaseToLatestVersion<ApplicationDbContext, Migrations.Configuration>();
    System.Data.Entity.Database.SetInitializer(initializer);
}

Now the database will automatically apply new migrations.

TODO: Step 3 Add a default admin user.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment