Yet Another Web API 2 Quick Start

The ASP.NET Web API 2 is a framework to create Web services — that is, the service sits on some machine waiting for a request (usually for data) from a Web page or a program, processes the request, and sends a response. Web API documentation is decent but here’s my personal quick start.

The goal is to create a dummy service that will compute the volume of a sphere. For example, the volume of a sphere with radius 2.0 is 33.49.

WebApiDemo

To make things slightly more realistic, the Web service will call a math library DLL to do the computation, simulating a call to an external resource such as a SQL database.

The first step is to create a math library. I used Visual Studio to create a C# Class Library named MyMathLib:

using System;
namespace MyMathLib
{
  public class GeoFuncs
  {
    public double pi;
    
    public GeoFuncs(double pi)
    {
      this.pi = pi;
    }

    public double CircleArea(double radius)
    {
      return this.pi * radius * radius;
    }

    public ResultHolder SphereVolume(double radius)
    {
      double v = (4.0 / 3.0) *
        this.pi * Math.Pow(radius, 3);
      ResultHolder answer = new ResultHolder();
      answer.Label = "Volume";
      answer.Result = v;
      return answer;
    }

    public class ResultHolder
    {
      public string Label { get; set; }
      public double Result { get; set; }
    }

  } // class
  
} // ns

The CircleArea() function just returns a simple numeric value but the SphereVolume() function returns a program-defined ResultHolder object. I did this because Web API treats simple types and complex types differently. Building the project creates a MyMathLib.dll library.

Next I launched a new instance of Visual Studio and created a Web API project. Briefly, File | New | Project | Templates | Visual C# | Web | (.NET 4.5) | ASP.NET Web Application, name = MyMathService, then Empty (Web API checked) | OK.

In the Solution Explorer window I right-clicked on the MyMathService project name and added a Reference to the MyMathLib.dll library.

Then I right-clicked on the Models folder and did an Add | Class. My code just creates a single, shared MyMathLib object for the service:

namespace MyMathService.Models
{
  public class MathLibAccess
  {
    // create an instance of a MyMathLib object
    // for use by Controller
    public static MyMathLib.GeoFuncs mathLib =
      new MyMathLib.GeoFuncs(3.14);
  }
}

Next, I right-clicked on the Controllers folder and did Add | Controller | Web API 2 Controller – Empty | Add, name = ResultController.

The code (with extra line breaks so my blog software doesn’t go crazy) is:

namespace MyMathService.Controllers
{
  public class ResultController : ApiController
  {
    //public double Get(double radius)
    //{
    //  double area =
    //  MyMathService.Models.MathLibAccess
    //  .mathLib.CircleArea(radius);
    //  return area;
    //}

    public HttpResponseMessage Get(double radius)
    {
      var v =
      MyMathService.Models.MathLibAccess.mathLib
      .SphereVolume(radius);
      return Request.CreateResponse(v);
    }
  }
}

If you want to Get a simple type, you just define a normal Get method. If you want to Get a program-defined class (the ResultHolder) you use an HttpResponseMessage and the Request.CreateResponse() method.

Next, I went to the App_Start folder and synced the WebApiConfig.cs file to the parameter name (radius) I used in the Get() method:

namespace MyMathService
{
  public static class WebApiConfig
  {
    public static void
      Register(HttpConfiguration config)
    {
      config.MapHttpAttributeRoutes();

      config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{radius}",
          defaults: new { radius =
            RouteParameter.Optional }
      );
    }
  }
}  

Next, I created a Web page to send requests and fetch responses. I right-clicked on the project name and did Add | New Item | Web | Visual C# | Web | HTML Page, name = index.html, Add. Here’s the code in an image (because my blog software hates HTML):

WebApiClient

There’s quite a bit going on here. A RESTful request looks like:

http://localhost:53458/api/Result/3.0/

Note the trailing forward-slash. A query string request looks like:

http://localhost:53458/api/Result?radius=3.0

With all the pieces in place I hit the F5 key, and after futzing around a bit with errors, got the Web service to work.

There are literally dozens of options that I didn’t mention here. Web services can be extremely complex. But this quick start will be enough for me to get going the next time I have to create a Web service.

This demo just creates a dummy service running locally on IIS Express. To publish the Web service, you can follow the steps at http://dotnetmentors.com/web-api/host-asp-net-web-api-in-iis-using-visual-studio-publish.aspx.

Advertisements
This entry was posted in Machine Learning, Miscellaneous. Bookmark the permalink.