ASP Web API Routing Basics

Web API has a default route of HOST/API/Controller but what if we don't want that. How do we change it? Well it's actually easy, so lets do it.

Routing in ASP Web API

Routing in Web API is very straight forward and if you have done any work in ASP MVC then it will be familiar it's just in a different place. Remember you can have WEB API and MVC co existing in the same web application. By having them in different routing tables it means you can change it as you want.

All source code is here

Routing Table

In the App_Start folder you will find WebApiConfig.cs you will find a method called register and you will see the default route

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

This is the default route, anything that comes in on API it will look for the {controller} name and pass the data there.

So lets change that, instead of using /api/ to pass it lets change it to /serversncode/ we do that by adding a new route

        config.Routes.MapHttpRoute(
            name: "ApiV2",
            routeTemplate: "serversncode/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Now when we run the Web API we have two routes we can do the default /api/ or a /serversncode/

The routing here is the same as for MVC so if you have played with those routes these are the same.

Web API has a default route of HOST/API/Controller but what if we don't want that. How do we change it? Well it's actually easy, so lets do it. Routing in ASP Web API Routing in Web API is very straight forward and if you have done any work…

Read More

ASP Web API POST JSON

Prevouisly on Serversncode we created a WEB API that created Data into a Azure Table storage. This had a POST method that accepts the parameters, ASP WEB API.

But what if we wanted to pass the data in as part of a JSON. Well lets do that. Source code is here

First up lets create our Player Class, Last Time we created the PlayerEntity class this is for our table Storage but we don't want to pass that around, we want a player class so we can pass that into the POST method.

In Models create a new Class Player

public class Player
{
    public string Sport_VC { get; set; }
    public string Club_VC { get; set; }
    public string First_Name_VC { get; set; }
    public string Last_Name_VC { get; set; }
    public string Position_VC { get; set; }
}

To make a clear break from this work and the last post we're going to create a new WebAPI Controller called PlayerJController.

    [HttpPost]
    public string Post([FromBody] Player record)
    {
        string sResponse = "";

        // Create the entity with a partition key for sport and a row
        // Row should be unique within that partition
        PlayerEntity _record = new PlayerEntity(record.Sport_VC, sRow);

        _record.Sport_VC = record.Sport_VC;
        _record.First_Name_VC = record.First_Name_VC;
        _record.Last_Name_VC = record.Last_Name_VC;
        _record.Club_VC = record.Club_VC;
        _record.Position_VC = record.Position_VC;

        return sResponse;
    }

I've cleaned the code above of the work we do to create the Azure table etc. Just to keep it simple.

.NET will handle the heavy lifting for us. If we open Postman now and create a new POST call to our new API method.

Test API

  • Change it to a Post Method
  • Select Body, and RAW type out the JSON body
  • Change the Application type to "JSON (application/json)
  • Enter the URL localhost:999090/API/PlayerJ

That's it when you run that it will send the JSON into the API method and you can work with it to create the player entity and store it in Azure Table storage.

Prevouisly on Serversncode we created a WEB API that created Data into a Azure Table storage. This had a POST method that accepts the parameters, ASP WEB API. But what if we wanted to pass the data in as part of a JSON. Well lets do that. Source code is…

Read More

ASP Web API with Azure Table Storage

Using ASP Web API with Azure table storage

We've already covered the basics of creating an ASP Web API project and the basics for Azure Table Storage

ASP WEB API intro

Azure Table Storage

For the sample code for this check out our GitHub

Now we're going to get into using both of these. Creating a simple ASP Web API to create data into an Azure Table storage and to get that data back out. We'll do some testing of the API with Postman

As earlier we're using Visual Studio 2015.

Lets get going

Create a Web API project

Create Web API Project

Add Azure Storage from nuget.

We'll create a new controller building on our last post on Azure Table storage. We'll go for a "PlayerController"

Create API Controller

Select "Web API 2 Controller" from the Add scaffold option.

In the model create an entity for Table Storage "PlayerEntity". The player entity will look the same as we had in our last post.

Player Entity

Now back to our controller, we want to create two methods a POST method to create a player and a Get method to get players for a sport.

    public List<PlayerEntity> Get(string sport)
    {
        List<PlayerEntity> _records = new List<PlayerEntity>();

        //Create a storage account object.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Retrieve a reference to the table.
        CloudTable table = tableClient.GetTableReference("player");

        // Create the table if it doesn't exist.
        table.CreateIfNotExists();

        // Get All Players for a sport
        TableQuery<PlayerEntity> query = new TableQuery<PlayerEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, sport));
        
        foreach (PlayerEntity entity in table.ExecuteQuery(query))
        {
            _records.Add(entity);
        }

        return _records;
    }

This is the same as we used in our last post on Azure table storage.

We create a storage account with a connection string.

The table client is created and this we check for the table "Player" if it doesn't exist we create it.

Azure Table storage is a partitioned database. For this demo we create a partition based on Sport. So we can create players for "Soccer", "Rugby" and "Hurling" and so on. The get method will then only return the players for the sport we want.

For the Post there are a few ways to pass parameters we'll keep it simple for now. We'll pass the parameters into the POST method.

    // POST api/Player
    public string Post(string sSport, string sRow, string sFirstName, string sLastName, string sClub, string sPostition)
    {
        string sResponse = "";

        // Create our player

        // Create the entity with a partition key for sport and a row
        // Row should be unique within that partition
        PlayerEntity _record = new PlayerEntity(sSport, sRow);

        _record.Sport_VC = sSport;
        _record.First_Name_VC = sFirstName;
        _record.Last_Name_VC = sLastName;
        _record.Club_VC = sClub;
        _record.Position_VC = sPostition;

        //Create a storage account object.
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_connectionString);

        // Create the table client.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

        // Retrieve a reference to the table.
        CloudTable table = tableClient.GetTableReference("player");

        // Create the TableOperation object that inserts the customer entity.
        TableOperation insertOperation = TableOperation.Insert(_record);

        try
        {
            // Execute the insert operation.
            table.Execute(insertOperation);

            sResponse = "OK";
        }
        catch (Exception ex)
        {
            sResponse = "Failed: " + ex.ToString();
        }
        return sResponse;
    }

With this Post method, we can take the parameters passed in and then create a player in our Table storage.

Testing with PostMan

We will use Postman to do the testing if you don't have it go get it and check out this post on using Postman

Our Get method is simple it takes a parameter of sport and then will return all the players in that sport.

In post man we create a GET Request to

http://*LOCALHOST*/api/Player?sport=soccer

This will return a list of all players in Soccer.

To test the POST method change the method in Postman to "POST"

http://*LOCALHOST*/api/Player?sSport=soccer&sRow=52&sFirstName=Chris&sLastName=Smalling&sClub=Man Utd&sPostition=CB

That's it, since we kept our POST simple we just need to pass the parameters and we can add the player to the Azure table.

Coming soon we'll start to work on our POST method and passing the parameters in different ways.

For the sample code for this check out our GitHub

Using ASP Web API with Azure table storage We've already covered the basics of creating an ASP Web API project and the basics for Azure Table Storage ASP WEB API intro Azure Table Storage For the sample code for this check out our GitHub Now we're going to get into…

Read More

ASP WebAPI

ASP Web API

ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. Using ASP.NET Web API you can create a HTTP RESTful services.

HTTP is not just for serving up web pages. It is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

Get Started

In Visual Studio create a new project and select "ASP.NET Web application" Under Web templates. (I'm using Visual studio 2015)

Create ASP Web API

On the ASP.NET template screen for .NET 4.6 Select "Web API" this will scaffold everything you need. So go ahead create your first project.

Once Visual Studio has created the project you will have 3 controllers AccountController, HomeController, ValuesController

WEBAPI Default Solution

ValuesController has already been created with sample code for the API.

Run the project in debug mode and in your browser Click the "API" option

http://localhost:*****/help

Will show a list of the API methods available.

With the values Controller we can see the break down of all the API Methods

http://localhost:*****/Help/Api/GET-api-Values

Will show you the break down of the method for Get, the parameters required and response.

Summary

This post covered the very basics of getting started with Web API in .net. We'll bring more posts that build on this post over the next few weeks.

ASP Web API ASP.NET Web API is a framework for building web APIs on top of the .NET Framework. Using ASP.NET Web API you can create a HTTP RESTful services. HTTP is not just for serving up web pages. It is also a powerful platform for building APIs…

Read More