Share via


Azure: Create and Deploy ASP.NET WEBAPI to Azure and Manage using Azure API Management

 


Abstract

In this article we will discuss basics of Azure API Management to manage our Web API.

Introduction

In this article we will discuss all basics of Azure Management to manage our Web API. Here we will not discuss about the Azure Management how it works and how we can create Virtual Machine, Create Cloud App and host Apps with Azure, although our focus will be stick only for Managing Web APIs using Azure Management.

Here we will

  • Create ASP.NET WEB API
  • Host/deploy our services to Azure
  • Manage our services using Azure API Management

Pre-requisite

To work with this article, we need:

  • Visual Studio 2013 or later (you can use community edition)
  • SQL Server 2012 or later (you can use Express edition)
  • Basic knowledge of ORM (we will use FluentNHibernate in our demo app)
  • Basic knowledge of ASP.NET WEB API
  • Basic knowledge of RESTful services
  • A valid Windows Azure subscription (if you do not have get a one month free subscription)

Lets develop a simple ASP.NET WEB API

To work with this article we need WEB APIs, so, as a first step, lets develop a very simple web api by following step-by-step instructions:

 

Step-1: Create ASP.NET WEB API Project

To start we are using simple ASP.Net project:

  • Start Visual Studio and select File->New->Project (or enter Ctrl + Shift + N)

 

  • From available dialog choose Web Templates -> Asp.Net MVC 4 Web Application
  • I named it as ‘CRUDWithWebAPI’ – you can choose your favorite one.
  • Select Empty Web API using Razor View Engine

 

(P.S.: Alternatively you can Select Create a unit test project – we are not discussing this topic here)

* *

Step-2: Visiting Folder Structure

After above step, we will see that our project template is ready and following is the default folder structure provided by template:

  • App_Data
  • App_Start: contain config classes required to initiate the app (eg. route collection etc.)
  • Controllers: controller of web api
  • Models: Contain model/classes
  • Scripts: all scripts and css
  • Views

 

(P.S.: We are not going into more explanation of each and every folder, mentioned above, as it is beyond the scope of this article.)

 

Step-3: Installing FluentNHibernate Support

To install FluentNHibernate support to project:

  • Open ‘Package Manager Console’ using View-> Other Windows
  • Now type ‘Install-Package FluentNHibenrate’ and hit enter

Wait until FluentNHibernate get installed.                  

Step-4: Working on Models, Mappings and Repository Pattern

In this step, we will create Model its mapping and will add a repository.

Adding Models and their Mappings

  • To add model, right click on Models folder from Solution explore and choose class name it ‘ServerData’

 



      public class  ServerData
   
                                {      
                              public virtual  int Id { get; set; }  
                              public virtual  DateTime InitialDate { get; set; }  
                              public virtual  DateTime EndDate { get; set; }  
                              public virtual  int OrderNumber { get; set; }  
                              public virtual  bool IsDirty { get; set; }  
                              public virtual  string IP { get; set; }  
                              public virtual  int Type { get; set; }  
                              public virtual  int RecordIdentifier { get; set; }  
                       }      

 

 

 

Adding Model Mappings

  • Add its mapping class, right click on Models folder from Solution explore and choose class name it ‘ServerDataMap’
public class ServerDataMap : ClassMap<ServerData>
 
{
public ServerDataMap()
{
 Table("ServerData");
   
 Id(x => x.Id, "Id").GeneratedBy.Identity().UnsavedValue(0);
   
Map(x => x.InitialDate);
Map(x => x.EndDate);
Map(x => x.OrderNumber);
Map(x => x.IsDirty);
Map(x => x.IP).Length(11);
Map(x => x.Type).Length(1);
 Map(x => x.RecordIdentifier);
   
}
 
}
·         Do not forget to add following namespace:
 
using FluentNHibernate.Mapping;
 

 

Adding Fluent NHibernate support to project

  • Add new folder and name it as ‘Helper’
  • Add a new class beneath ‘Helper’ folder and name it as ‘NHibernateHelper’

In this class we need to configure NHibernate and build all sessionfactory so, our application will interact with database:

private static  void CreateSessionFactory()
{
                        _sessionFactory = Fluently.Configure()
 
                                    .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString).ShowSql)
 
                                    .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ServerData>())
 
                                    .ExposeConfiguration(cfg => new  SchemaExport(cfg).Create(false, false))
 
                                    .BuildSessionFactory();
 
}

We are not going to discuss all these stuff in details as these are beyond the scope of this article.

  • Create a new folder beneath ‘Models’ and name it as ‘Persistance’
  • Add one Interface ‘IServerDataRepository’ under ‘Persistance’

** **

public interface  IServerDataRepository
    {
        ServerData Get(int id);
        IEnumerable<ServerData> GetAll();
        ServerData Add(ServerData serverData);
        void Delete(int id);
        bool Update(ServerData serverData);
  
    }
  • Add one class ‘ServerDataRepository’ under ‘Persistance’ and implement ‘IServerDataRepository’
public class  ServerDataRepository : IServerDataRepository
    {
  //method implementation goes here    
    }

 

Now, we have ready with our Repository to start play.

P.S.: refer: http://msdn.microsoft.com/en-us/library/ff649690.aspx  for more details on Repository Pattern.

 

Step-5: Add WEB API Controller

In this step, we will add an API controller and will add all necessary resources.

  • Right click on folder ‘Controllers’ and add a new controller name it as ‘ServerDataController’ (select an empty controller)
  • It would look like:
public class  ServerDataController : ApiController
 
    {
 
    }
  • Add following line of code (it will initiate our repository).

 

static readonly IServerDataRepository serverDataRepository = new ServerDataRepository();

 

P.S.: Please note that in this article/demo we are not going to implement any DI pattern or Inversion of Control (IOC) framework.

We all are set to go now:

public IEnumerable<ServerData> GetServerData()
 
            {
 
                        return serverDataRepository.GetAll();
 
            }

See above defined method, why we add ‘Get’ suffix, this is a good practice to add ‘Get’ with your method name, by convention it maps GET request.

This method do not have any parameter, so, you can say this maps uri which does not contain ‘id’ parameter.

  • Add following method to get ServerData by id. This is an optional parameter as defined in our route and asp.net Web API framework automatically convert its type to int.
  • It will throw ‘HttpResponseExceptionexpception if it is not valid (in following method we converted the exception to 404 NOT Found exception)
public ServerData GetServerDataById(int id)
 
            {
 
                        var serverData = serverDataRepository.Get(id);
 
  
 
                        if (serverData == null)
 
                                    throw new  HttpResponseException(HttpStatusCode.NotFound);
 
  
 
                        return serverData;
 
            }

 

  • Following method is to get ServerData by its type:

 

public IEnumerable<ServerData> GetServerDataByType(int type)
 
            {
 
                        return serverDataRepository.GetAll().Where(d => d.Type == type);
 
            }
  • To invoke above method we need to define new routes in ‘WebApiConfig.cs’ as follows:

 

config.Routes.MapHttpRoute(
 
                name: "ProductByType",
 
                routeTemplate: "api/{controller}/type/{type}"
 
            );

 

  • Similarly for :
public IEnumerable<ServerData> GetServerDataByIP(string ip)
 
        {
 
            return serverDataRepository.GetAll().Where(d => d.IP.ToLower() == ip.ToLower());
 
        }
 
config.Routes.MapHttpRoute(
 
                name: "ProductByIP",
 
                routeTemplate: "api/{controller}/ip/{ip}"
 
            );

 

  • Here we are going to delete serverdata using this method:

 

public void  DeletServerData(int  id)
 
            {
 
                        var serverData = serverDataRepository.Get(id);
 
  
 
                        if (serverData == null)
 
                                    throw new  HttpResponseException(HttpStatusCode.NotFound);
 
                        serverDataRepository.Delete(id);
 
            }
  • Lets add a new method to our controller to add new record of ServerData

 

public ServerData PostServerData(ServerData serverData)
{
   return serverDataRepository.Add(serverData);
}

Will above method work? Of course, it works but it’s not an ideal or say it’s not quite complete, why?

  • In above suffix is ‘Post’ which sounds it sends Http POST request
  • Also its noticeable parameter is of type ‘ServerData’.
  • Complex type parameters are deserialized from the requested body when we used Web API, also, we can say we expect serialized input from client like either in xml or JSON.

 

In above method, we miss followings from HTTP response:

  • Response code: by default it is 200 (Ok) but as per HTTP1.1 protocol, the server should reply 201 (created), while POST request results in the creation of a resource
  • Location: server should include the URI of the new resource in the location header of the response, whenever it creates a resource.
  • So, we can implement this as defined in following methods:
public HttpResponseMessage PostServerData(ServerData serverData)
 
            {
 
                        serverData = serverDataRepository.Add(serverData);
 
  
 
                        var response = Request.CreateResponse<ServerData>(HttpStatusCode.Created, serverData);
 
  
 
                        var uri = Url.Link("DefaultApi", new  { id = serverData.Id });
 
                        response.Headers.Location = new  Uri(uri);
 
  
 
                        return response;
 
  
 
            }

 

  • Finally, we need to add an update method, it’s a straight forward:

 

public void  PutServerData(int  id, ServerData serverData)
 
            {
 
                        serverData.Id = id;
 
  
 
                        if (!serverDataRepository.Update(serverData))
 
                                    throw new  HttpResponseException(HttpStatusCode.NotFound);
 
            }

From above, we can understand that WEB API matches this method to PUT request, above method is having two parameter id and serverdata. So, it is taken from URI path and serverdata is deserialized from the request body.

P.S.: By-default Web API framework takes simple parameter types from the route and complex types from the request body.

Step-6: Set default result output type

We need result in JSON by default, lets add following line either in Global.asx.cs file or in the file where you are registering routes.

 

//return JSON response by default
 
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

 

Deploy our services to Azure

Lets now, deploy our above created services to our Azure server.

  • From Solution Explorer Right click and Publish

 

  • We are deploying/publishing our ASP.NET WEB API as a Azure Website so, we can get a robust endpoint – we will discuss about this in upcoming sessions/articles.
  • And then click on Publish

 

 

Now, we have deployed our services, we need to setup Azure API Management portal.

Working with AZURE MANAGEMENT

Now, we are ready with our WEB API to host/manage these with AZURE MANAGEMENT. If you do not have any Azure subscription try a trial one from here: http://azure.microsoft.com/en-in/pricing/free-trial/

 

Create instance of API Management

First, we need to create an API Management instance. Follow these step(s):

 

  • Now from NEW API MANAGEMENT SERVICE

 

  • In URL textbox, specify a unique sub-domain name to use for the service URL.
  • Choose the desired Subscription and Region for your service instance. After making your selections, click the next button.

 

  • Enter Organization name and E-mail id

 

  • API Management service instances are available: Developer, Standard and Premium. By default, new API Management service instances are created using the Developer tier. To select the Standard or Premium tier, check the advanced settings checkbox and select the desired tier on the following screen.

(P.S.: Premium could not available in promotional and Free/Trial accounts)

  • Finally, click to create

 

Here, we are on our API MANAGEMENT screen.

 

  • Click on MANAGE from bottom of your dashboard

 

  • To create our first API, click APIs from the API Management menu on the left, and then click Add API.

 

In this screen, what we did?

  • We provide a unique name to our API as ‘Demo’ into the Web API Title textbox. Web API Title provides a unique and descriptive name for the API. It is displayed in the developer and management portals.
  • We provide actual address where our WEB API hosted, please refer to above section, where we discussed about the deployment of our WEB API to Azure. http://crudwithwebapi.azurewebsites.net/  into the Web service URL. Web service URL references the HTTP service implementing the API. API management forwards requests to this address.
  • We provide a suffix as ‘demo’ to our API. Web API URL suffix is appended to the base URL for the API management service. Our APIs will share a common base URL and be distinguished by a unique suffix appended after the base.
  • Web API URL scheme determines which protocols can be used to access the API. HTTPs is specified by default.

(P.S.: Here we selected both HTTP and HTTPs protocols – will discuss about this in coming sections/series of articles)

 

  • The API section has six tabs.
    • The Summary tab display basic metrics and information about the API.

 

  • The Settings tab is used to view and edit the configuration for an API, including authentication credentials for the back-end service.

 

 

  • The Operations tab is used to manage the API's.

 

  • The Security tab can be used to set Proxy Authentications using Basic and Mutual certificates or can be used to set OAuth 2.0 – we will not discuss this in details.

 

  • The Issues tab can be used to view issues reported by the developers using our APIs.

 

 

  • The Products can be used to create and manage products for our APIs – in this article we will be not discussing this section.

 

 

Add an operation

  • Go to Operation tab
  • We did not create anything so, this tab will be empty
  • Click on ‘Add Operation’ to add new API operation

In our Web APIs we have following resources:

 

  • Lets add our very first API resource as an operation in API Management portal

 

 

 

In above screen, we specified:

  • HTTP verb as a GET – for retrieve the things
  • URL template – our actual resource of Web API (as mentioned in the above table)
  • For this operation we did not have any Request parameters so, no need to define any one
  • Note that we can give parameters as query parameter or Body
  • Under RESPONSES we select HTTP STATUS code 200 which is ‘OK’ means when everything will be went fine it will return specified application/json format

We are done with our APIs work. We have hosted our Web API with Azure API Management. Now, these are ready to use or to consume by developers.

Developers will use Azure API Management developer portal to use/see all APIs related documentations.

 

Unfortunately, yet we did not registered any user as a developer, lets follow these steps to register our API products.

 

(P.S.: we will discuss in coming session – how to setup different products and mange users with Azure API Management).

 

Subscribe to our created API products

To create a subscribers, we can do it by invitation and with the use of Administrator portal of API Management.

 

 

 

Here, we are using Developer portal where we have already invited/shared our development portal links to our end-users or targeted audience for development.

 

Discussing API MANAGEMENT Developer Portal

In this section we are going to discuss all about Developer portal in brief.

 

This will be the default Home page for every developer. Developers, can go through app APIs documentations, your API Blog (if created) and other application (if you are providing for any Product).

As we are not going into details for Developer Portal, let’s sign up as a Subscriber.

  • Click on SIGN IN  from Right-Top
  • From Sign In page (as we do not registered yet) Click on Sign up now

 

 

  • Enter all specified details and click on Sign up

 

 

 

 

 

  • You need to verify your email

 

 

 

  • After verification of your email, Log In to developer portal, click on API link

 

  • Subscribe to a Product

 

 

 

From Administrator Portal click Users and approve subscription for user

 

 

  • Click on Demo API from Developer Portal
  • Here you will get all APIs listed under Demo

 

 

  • Click on First Get ServerData

 

 

 

  • Here you can see that our Request URL required a subscription-key which is nothing just our Primary/Secondary API key, provided by Azure API MANAGEMENT as per subscription.

Testing APIs

We can test our hosted APIs via any external Client or using Console from within API Developer Poartal.

  • Click on Open Console from current Get ServerData API
  • Here you should need API key, select either Primary or Secondary.

 

  • After hitting HTTPGET (this is a GET Resource) you will get the related output.

 

 

 

 

We have done with all the things to Manage Web API with Azure API Management.

Conclusion

In this article we discussed all about Creation of ASP.NET Web API, hosting to Azure and Management using Azure API Management.

In coming sessions/articles we will discuss about more about advanced topics/features of Azure API Management.

Complete source code is available at: https://github.com/garora/somestuff/tree/master/CRUDWithWebAPI

See Also