If you’ve ever worked in an overly restrictive environment, you know you have to come up with some workarounds to get your job done. I worked in such and environment and ran into a problem developing some front end pages to work with an API, but I didn’t want to use live data. Here’s a solution I came up with and I decided to write it out and explain it in hopes it will help others.
Tools Needed for this Tutorial (both free of charge):
Why a self hosted API?
When you’re developing front end stuff its always nice to have a development environment to work against rather than live data, as I explain in smell it before you eat it. But what if a development environment isn’t available? What if you can’t install IIS on your machine either? In that case you make a self hosted API to send fake calls to, and try to replicate the behavior.
For this tutorial I’m going to assume you already know all about REST and some ASP.Net API basics.
Find out what you need.
First you need to find out which API functions you’ll need and map them out, because you’re going to have replicate them here, on a small scale. For the demo, we’re going to make something that stores a listing of books.
We want to be able to have some basic CRUD methods for it, so let’s set it up. For this you will need a copy of Visual Studio Professional, or Express 2013 for Windows Desktop. That’s what I’ll use for this demo.
1. Create the Project
Select File -> New Project
Choose “Console Application”
Right click on your project and select “Manage NuGet Packages”
Search the Online Packages for “Microsoft ASP.Net Web API Self Host” and install the assemblies.
2. Set up the executable
Next we’ll want to add configuration data, so in Program.cs add the following using statements:
And then inside in the static void Main() function add:
Note that the port can be anything you want it to be.
Now create an instance of the HttpSelfHostServer passing in your config object as the parameter:
Now create a task that calls the OpenAsync method and set the task to Wait:
Next, we’ll want to output something to console to let you know it’s started, and put a Console.ReadLine in there to make sure it stays open until you want it to quit.
Note: At this time you can have a running service, but you must be running Visual Studio as an administrator. Now, if you’re in a restricted environment like I was you can’t do that, so you just have to code it with blind faith that it will work. You can run the finished product once it’s done, but if you are allowed to run as admin you can debug and test better.
3. Set up routing
Ok, so much of this doesn’t do you a lot of good until you can route your requests.
Open up the package manager again (Right click on your project and select “Manage NuGet Packages”) and search for ”Attribute Routing Self-Hosted”. Install the AttributeRouting(Self-Hosted Web API) package.
Now, open up Program.cs and add the following:
This will handle the routing for your application.
4. Create a Model
In this tutorial we’re going to create a storage space for some books. Create a class that looks like this:
1 2 3 4 5 6 7
This will obviously store some simple attributes for our books.
5. Create a Controller
Let’s create a class called BookController that extends the ApiController:
In that class we’ll want to create a few demo books every time it starts. We do this by creating a List of type book, and adding a few instances into it to start out:
1 2 3 4 5 6 7 8 9 10 11 12 13
Next, we’ll want to create a method to retrieve all books:
1 2 3 4
This will return all the books in our list. Let’s open up fiddler and see what that looks like:
So as you can see, a list of our items is returned with a GET request. This may be all you need, but if you need REST services, continue on.
6. Setting up REST actions
in our BookController, you’ll want to add a few more methods to add update and delete items.
Retrieve a book by ID (GET)
Let’s make it so we can select a book by it’s Id. Add a method to the controller that looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
This overrides the Get method, so if you pass it an Id, it will return some details for that book. As you can see if it does not find an ID it returns a 404 error, with a custom response.
Add a new book (POST)
To add a new book, we want to create a method that takes a POST command, and gets the JSON object from the body of the request. To that, add the following method:
1 2 3 4 5 6 7
In order to add a new item to our list, we’ll need to change the request in Fiddler to a POST, and set the Content-Type:
And we’ll need to send it a JSON object, like this:
Your composer should look like this:
Once you submit, run another GET request, and you’ll see the new object:
It’s that easy! The next are even easier.
Update a book (PUT)
In this method we’re going to update a book using the PUT command.
Add the following method to your controller:
1 2 3 4 5 6 7 8 9 10 11 12
Now, if you run a GET in Fiddler, you should see a set of results as they are set by default:
Since it’s a new instance the one we added will not be there.
In Fiddler (or whatever program you’re using) change the request to a PUT, and add an ID at the end (for the record you want to change). Then set the Content-Type to application/json and send the JSON string we used earlier. It should look like this:
Once you send the put request, now send a GET and you’ll see the updated information:
Remove a book (DELETE)
This one is really easy:
1 2 3 4 5 6 7 8 9 10
Now, just set fiddler to delete an id and send it:
And it’s deleted!
7. Build and use it!
So now that your application is ready, you can build and executable and use it for development.
Just build it, then look in your /bin/release folder and run it from there!
Whenever it’s running you can connect to it like a standard web service.
So what’s the point of all this?
After reading this it might seem like a lot of work, but after you’ve done it a few times it’s really quick to whip it up. You might be asking, what’s the point?
Since you control what data is seeded in, you can write better unit tests for it knowing exactly what to expect. Since it’s only stored in memory, it’s really fast and resets as soon as you restart the executable. This can drastically speed up the development time and create better test cases.
Let me know if you use this, the code is on GitHub feel free to fork it and expand on it!