ASP .NET Web API: A Gentle Introduction

This article was originally posted here at Programmer’s Ranch on 1st August 2014.

Hello! ūüôā

Last year, we saw how to intercept HTTP requests in Wireshark, and also how to construct them. As you already know, HTTP is used mainly to retrieve content from the Web; however it is capable of much more than that. In this article, we will learn how HTTP can be used to expose an API that will allow clients to interact with back-end services.

Ideally, you should be using Visual Studio 2013 (VS2013) or later. If you’re using something different, the steps may vary.

Right, so fire up VS2013, and create a new ASP .NET Web Application. In VS2013, Microsoft united various different kinds of web projects under a single banner, which is what people mean when they refer to something called “One ASP .NET“. So there isn’t that much choice in terms of project types:

webapi-intro-newproject

You are given some sort of choice once you click “OK”, however:

webapi-intro-newproject-template

At this stage there are various web project types you can choose from, and in this case you need to select “Web API”. You’ll notice that the “MVC” and “Web API” checkboxes are selected and you can’t change that. That’s because Web API is somewhat based on the ASP .NET MVC technology. Web API is sort of MVC without the View part, so discussing MVC is beyond the scope of this article; however just keep that in mind in case you ever dive into MVC.

Once you click “OK” and create your project, you’ll find a whole load of stuff in your Solution Explorer:

webapi-intro-newproject-created

This may already seem a little confusing. After all, where should we start from? Let’s ignore the code for a moment and press F5 to load up our web application in a browser. This is what we get:

webapi-intro-initialrun-homepage

You’ll notice there is an “API” link at the top. Clicking it takes you to this awesome help page, where things start to clear up:

webapi-intro-initialrun-help

It turns out that the Web API project comes with some sample code that you can work with out of the box, and this help page is telling you how to interact with it. If you look at the first entry, which says “GET api/Values”, that’s something we can point the browser to and see the web application return something:

webapi-intro-initialrun-values

And similarly, we can use the second form (“GET api/Values/{id}”) to retrieve a single item with the specified ID. So if you point your browser to /api/Values/1, you should get the first one:

webapi-intro-initialrun-values-1

That’s all well and good, but where are these values coming from? Let’s go back to the code, and open up the Controllers folder, and then the ValuesController in it:

webapi-intro-initialrun-valuescontroller

You can see how there is a method corresponding to each of the items we saw in the help page. The ASP .NET Web API takes the URL you enter in the web browser and tries to route the request to a method on a controller. So if you’re sending a GET request to /api/Values/, then it’s going to look for a method called Get() in a controller called ValuesController.

Notice how the “Controller” part is omitted from the URL. This is one of many things in Web API that you’re expected to sort of take as obvious – Web API uses something called “convention over configuration”, which is a cool way of saying “it just works that way, and by some kind of magic you should already know that, and good luck trying to change it”. If you’ve read my¬†article about Mystery Meat Navigation, part of which addresses the Windows 8 “content over chrome” design, you’ll notice it’s not very different.

And since, at this point, we have digressed into discussing big buzzphrases designed to impress developers, let’s learn about yet another buzzword: REST. When we use HTTP to browse the web, we mainly use just the GET and POST request methods. But HTTP supports¬†several other request methods. If we take four of them – POST, GET, PUT and DELETE, these map quite smoothly to the CRUD (Create, Read, Update and Delete) operations we know so well from just about any business application. And using these four request methods, we can build APIs that allow us to work with just about any object. That’s what is meant by¬†REST, and is the idea on which the ASP .NET Web API is built. “How I Explained REST to My Wife” is a really good informal explanation of REST, if you want to learn more about it. The irritating thing is that the concept is so simple, yet it’s really hard to find a practical explanation on the web on what REST actually means.

To see this in action, let’s rename our ValuesController to BooksController so that it’s less vague. We’ll also need a sort of simple database to store our records, so let’s declare a static list in our BooksController class:

        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"
        };

Now we can change our Get() methods to return items from our collection. I’m going to leave out error checking altogether to keep this really simple:

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];
        }

We can test this in the browser to see that it works fine:

webapi-intro-books-get

Great! We can now take care of our Create (POST), Update (PUT) and Delete (DELETE) operations by updating the methods accordingly:

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);
        }

Good enough, but how are we going to test these? A browser uses a GET request when you browse to a webpage, so we need something to send POST, PUT and DELETE requests. A really good tool for this is Telerik’s¬†Fiddler.¬†Postman, a Chrome extension, is also a pretty good REST client.

First, make sure that the Web API is running (F5). Then, start Fiddler. We can easily send requests by entering the request method, the URL, any HTTP headers, in some cases a body, and hitting the Execute button. Let’s see what happens when we try to POST a new book title to our controller:

webapi-fiddler-post1

So here we tried to send a POST request to http://localhost:1817/api/Books, with “The Art of War” in the body. The headers were automatically added by Fiddler. Upon sending this request, an HTTP 415 response appeared in the left pane. What does this mean? To find out, double-click on it:

webapi-fiddler-http415

You can see that HTTP 415 means “Unsupported Media Type”. That’s because we’re sending a string in the body, but we’re not specifying how the Web API should interpret that data. To fix this, add the following header to your request in Fiddler:

Content-Type: application/json

When you send the POST request with this header, you should get an HTTP 204, which means “No Content” – that’s because our Post() method returns void, and thus nothing needs to be returned. We can check that our new book title was added by sending a GET request to http://localhost:1817/api/Books, which now gives us the following in response:

webapi-fiddler-after-post

We can similarly test PUT and DELETE:

  • Sending a PUT request to http://localhost:1817/api/Books/1 with “The Prince by Niccolo’ Machiavelli” in the body updates that entry.
  • Sending a DELETE request to¬†http://localhost:1817/api/Books/0 deletes “How to Win Friends and Influence People”, the first book in our list.
  • Sending a GET request to¬†http://localhost:1817/api/Books again shows the modified list:

webapi-fiddler-after-all

Fantastic! In this unusually long article, we have learned the basics of working with the ASP .NET Web API. Lessons learned include:

  • The ASP .NET Web API is based on the REST concept.
  • The REST concept simply means that you use HTTP POST, GET, PUT and DELETE to represent Create, Read, Update and Delete operations respectively.
  • For each object you want to work with, you create a Controller class.
  • Appropriately named methods in this Controller class give you access to the CRUD operations mentioned above.
  • Use Fiddler or Postman to construct and send HTTP requests to your Web API in order to test it.
  • Add a content type header whenever you need to send something in the body (POST and PUT requests).

Thanks for reading, and please share this with your friends! Below is the full code of the BookController class for ease of reference.

    public class BooksController : ApiController
    {
        private static List<string> books = new List<string>()
        {
            "How to Win Friends and Influence People",
            "The Prince"
        };

        // GET api/Books
        public IEnumerable<string> Get()
        {
            return books;
        }

        // GET api/Books/1
        public string Get(int id)
        {
            return books[id];
        }

        // POST api/Books
        public void Post([FromBody]string value)
        {
            books.Add(value);
        }

        // PUT api/Books/1
        public void Put(int id, [FromBody]string value)
        {
            books[id] = value;
        }

        // DELETE api/Books/1
        public void Delete(int id)
        {
            books.RemoveAt(id);
        }
    }

Determining the bitness (x86 or x64) of a DLL

This article was originally posted here at Programmer’s Ranch on 28th September 2014.

Hello guys and gals! ūüôā

In this article, we’re going to tackle a pretty frustrating scenario: making sure all your .NET assemblies or even native DLLs target the same architecture. At the time of writing, applications tend to be targeted at x86 or x64 architectures, or both. However, mixing DLLs or executables compiled for different architectures is a recipe for disaster. This kind of disaster, in fact:

bitness-badimageformatexception
That’s a BadImageFormatException, saying:

An unhandled exception of type ‘System.BadImageFormatException‘ occurred in Microsoft.VisualStudio.HostingProcess.Utilities.dll
Additional information: Could not load file or assembly ‘ClassLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

This is why it’s happening:

bitness-mixed-architecture

That’s a very, very stupid thing to do, having an x64 console application depend on an x86 class library (or DLL). Remember:

bitness-dont-mix-architectures

Great, now you know. But you’re bound to run into the BadImageFormatException problem anyway, because while it’s easy to control the bitness of the assemblies in your project, you often depend on DLLs provided by third parties, and their own bitness isn’t clearly defined. Unfortunately, you can’t rely on rightclick -> Properties -> Details because that doesn’t give you the bitness at all.

Fortunately, however, there are tools you can use to find out what architecture those DLLs are compiled for.

Let’s start off with .NET assemblies. If the DLL in question is a .NET assembly, you can¬†use the corflags utility¬†to find out the bitness. corflags is part of the Visual Studio developer tools, so you’ll first need to start a Visual Studio developer command prompt (see¬†this StackOverflow thread¬†or search Windows for CorFlags.exe¬†in case you can’t find one from the Start menu).

Once you’ve located CorFlags.exe or have a Visual Studio developer command prompt, runCorFlags.exe¬†with the full path to the DLL you want to inspect, and check the 32BIT¬†setting in the output:

bitness-corflags

Now CorFlags.exe works great to find out the architecture of a .NET assembly, but can’t tell you the architecture of a native DLL. This is what happens if you try to use it with SDL2.dll, for instance:

bitness-corflags-native

For unmanaged/native DLLs, we can instead¬†use dumpbin. This will spit out a bunch of information, so you can find the architecture quickly if you filter the information by including only the line containing the word “machine”, as the linked Stack Overflow answer suggests:

bitness-dumpbin

So there you go – this article has presented two different ways to check the bitness or CPU architecture of managed and unmanaged DLLs respectively, which helps when troubleshooting those dreaded BadImageFormatExceptions. In reality this article is a consolidation of the information in the two Stack Overflow threads linked above, and I would like to thank the authors because I have found their tips useful on many occasions.

Authenticating with Active Directory

This article was originally posted here at Programmer’s Ranch on 14th March 2014.

Hi! ūüôā

If you work in a corporate environment, chances are that your Windows machine is connected to a domain based on¬†Active Directory. In today’s article, we’re going to write a very simple program that allows us to verify a user’s credentials for the domain using Active Directory.

In order to try this out, you’re going to need an Active Directory domain. In my case, I installed Windows Server 2008 R2 and¬†followed these instructions¬†to set up a domain, which I called “ranch.local”. You may also be able to connect to your domain at work to save yourself the trouble of setting this up.

Let us now create a new Console Application using either SharpDevelop or Visual Studio. After adding a reference to System.DirectoryServices.AccountManagement, add the following statement near the top of your Program.cs file:

using System.DirectoryServices.AccountManagement;

Next, remove any code in Main() and add a simple prompt for the username and password to authenticate against Active Directory:

// prompt for username

Console.Write("Username: ");
string username = Console.ReadLine();

// prompt for password

Console.Write("Password: ");
string password = Console.ReadLine();

For the authentication part, we can use a simple method described here. After obtaining a reference to the domain using the PrincipalContext class (specifying the domain as a parameter), we simply use the ValidateCredentials() method to perform the authentication. This gives us a boolean value indicating whether the authentication was successful or not.

// authenticate

using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "RANCH"))
{
    bool authenticated = pc.ValidateCredentials(username, password);

    if (authenticated)
        Console.WriteLine("Authenticated");
    else
        Console.WriteLine("Get lost.");
}

At this point, we need only add a simple statement to wait for user input before letting the application terminate:

Console.ReadLine();

Now, we can build our application and test it on the server (or on any machine that is part of the domain). First, let’s try a valid login:

csadauth-valid

Very good! And now, a user that doesn’t even exist:

csadauth-invalid

Excellent! As you can see, it only takes a couple of lines of code to perform authentication against Active Directory. I hope you found this useful. Follow the Ranch to read more articles like this! ūüôā