Web Service APIs in dotnet C# made easy with ApiController: Part 1

This entry is part 1 of 3 in the series .NET Web Services

Setting up your web service

Dotnet’s stuff for developing web applications includes an inheritable class called ApiController. This makes it easy to develop REST-style web services, either for standalone API servers or in the context of larger servers. To start using ApiController, however, requires navigating lots of Microsoft documentation; as of early 2020 that documentation is pretty much all machine-generated and doesn’t give any context.  MS’s dotnet class documentation should have a banner saying Lasciate ogne speranza, voi ch’intrate.  I wished I had Virgil along, like Dante did, to help me navigate it.

Here are the steps I followed to make a web service. Let’s call it the “yoyo” service.

Controller

First, create a C# source file called YoyoController.cs. It typically goes in your project’s Controlllers directory, but it can go in App_Classes or anywhere. Its file name, and the class it defines, must end in Controller.cs or nothing works.  Visual Studio’s “Add > ” menu has a choice, near the bottom, called “Web API Controller Class (v2.1)” or something similar. The code it generates looks something like this:

using System.Collections.Generic;
using System.Web.Http;

namespace Yoyodyne.App_Classes {
    public class YoyoController : ApiController {
        public IEnumerable<string> Get() {
            return new string[] { "value1", "value2" };
        }
    }
}

Configuration

Next, we need to create the file called `App_Start\WebApiConfig.cs` in our project to tell the dotnet web server to handle these routes. It should look like this

using System.Web.Http;
namespace www {
    public static class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional } );
        }
    }
}

Try it out

Now you should be able to use curl to try out the GET service by hitting /api/yoyo. This assumes you’re using the Visual Studio debugger on your local machine, which makes http://localhost:64410 serve the site you’re developing.

curl -H "Accept: application/json" localhost:64410/api/yoyo

Here, curl returns the result made by return new string[] { "value1", "value2" }; in JSON. It is, of course, ["value1","value2"].

You could also get it in XML if you wanted, like this.

curl -H "Accept: application/xml" localhost:64410/api/yoyo

It gives back this XML.

<ArrayOfstring
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>value1</string>
  <string>value2</string>
</ArrayOfstring>

Let’s stick with JSON from here on. JSON is the default returned type from these ApiController services. XML contains the same stuff, but in a far more verbose way.

Up Next

We’re up and running with our little web service. It’s time to refine it a bit. Let’s make it able to return an HTTP Status Code along with its result. We’ll also need to handle query parameters and cookies.

Series NavigationWeb Services in C#: Status, Parameters, Cookies >>

Leave a Reply

Your email address will not be published. Required fields are marked *