Archive | WEB API RSS for this section

How To: Convert ASP.NET Web API to Azure API app

In my last post, I introduced and discussed about the new azure API apps.  It’s really nothing more than your web API with a new way and form to expose the metadata so to speak.  Its actually a web app with other additional features for hosting. Azure API  is hosted within a web app.

In the pipeline to Azure API app, there a gateway which performs other stuff before reaching the Azure API app. The gateway is just another web app able to perform extra functionality like authetication with providers.

Every resource group with that contains an API app also includes a gateway. The azure API app expose there metadate via a new representation swagger. Its a new powerful representation of RESTful API.

In this post we are looking at how to convert an already existing ASP.NET web api to azure api app. I will be using visual studio 2013.

Open visual studio 2013, and create a new ASP.NET Web api.


To keep things simple, I am not using any authentication in this post. We will make a few changes to ValuesController, make sure it look like show below

public class StudentController : ApiController
public IHttpActionResult Get()
var students = Students();

return Ok(students);

private List<Student> Students()
var students = new List<Student>();
IGenerationSessionFactory factory = AutoPocoContainer.Configure(
x =>
x.Conventions(c => { c.UseDefaultConventions();});

//Create a session
IGenerationSession session = factory.CreateSession();
students = session.List<Student>(50)
.Impose(x => x.FirstName, "Bob")
.Impose(x => x.FirstName, "Alice")
.Impose(x => x.LastName, "Pius")
.Random(10).Impose(x => x.LastName, "Peter")
.                                                  All().Get().ToList();

return students;

In our code we are using “autopoco” package to generate object to test with. So far this is just the normal ASP.NET web api. You can run the application and hit “http://localhost:26467/api/Student&#8221; and you will see the response of 50 students.

So how do we convert it to azure API app? Good question, and the essence of this post. To do that you simply add a new package called “swashbuckle” as shown below. Go package manager and search for “swashbuckle”


When this is installed a new file should be added in your App_Start, “SwaggerConfig.cs”. Ensure your solution looks like below


That’s the file that makes your expectations come true. Nothing much, nothing less. So run you application and hit the following url, “http://localhost:26467/swagger&#8221; which takes to a screen like below:


If your screen looks like above then everything so far looks good. So this generates a documentation of all the api operations in the project, you need to know it uses the same pipeline as how ASP.NET WEB api generate help pages.  Click “Try it out!” and you will see a json response from the “GET” operation.

But where is the metadata? Navigate to “http://localhost:26467/swagger/docs/v1&#8221;, and this will generate a metadata file which is json in nature. We will talk on how to use this metadata file to generate a client sdk and other uses.


So from the image above.

1. Paths holds a collection of the API controllers in the projects

2. Indicate a API controller in our project “/api/Student”

3. Within every API controller, all available operations tagged with the http verb are listed.

4. The responses the operation supports.

That’s it!! 🙂 We have managed to convert/enable an ASP.NET Web api to a azure api app.

Source code can be on github

Quick look at azure app services

For a good period of time, azure has been offering azure websites and mobile services among others like biztalk services. Recently as part of the Azure SDK 2.5.1 release they have used a new term “App services”. As I tried to understand what this means, I was abit confused but found that its not a completely new term, its a combination what we know, with added features and advancements

App services basically is a collection of the things we already know and new additions that will help you with new integrations, building of rich, engaging and intelligent applications to help you scale as your business grows.

In the application services azure websites are termed “Web apps” while mobile services are termed “mobile apps”. If you visit your azure account you should be able to see these changes. Basically the current websites can easily be converted to web apps and therefore you are not going to rewrite your websites.

App services therefore contains

  1. Web apps
  2. Mobile apps
  3. Logical apps
  4. API apps.
  5. BizTalk API Apps

API apps

This new feature add on top of the ASP.NET Web API extending it with swagger metadata and an easy way to manage on the azure portal. It helps you easily build and consume API in the cloud The API Apps are behind a gateway which manages various add-on functionalities like authentication and update policies.

The gateways are created when you create a new API  App and they live in stardand resource groups. Just like we generate the WSDL information with svcutil, you can easily the swagger metadata on your Azure API Apps on visual studion by adding “/swagger/docs/v1” to your browser address.

Another functionality is that you can package your Azure API App and upload it to azure market place for other consumers to use it.

As we will see in future posts, you can easily generate your Azure API App sdk in a few click. Existing ASP.NET Web API can be converted to Azure Web API without any complexity by simply adding Azure App API SDK.

With  API Apps, you can easily on the azure portal define the access levels for you API App. There are three access levels namely

  • Public (Anonymous) -Meaning does not require any form of authentication to access
  • Internal -Only apps in your subscription can access and not available for public access
  • Public (Authenticated) -Publicly available but you require authentication for access.

With API Apps, from azure portal you choose, by a click how you intend to update in case the API App is updated. You can choose from Off (You dont need update), Inherit  and On meaning it will auto-update.

Something to note is that when you get an API app from the market place, you get an independent instance of that API App in your subscription, and there it runs in “isolation” from others, hence the reason to update when major or minor updates are done to the source package in the market place. 🙂

Web Apps

As mentioned earlier this were the formerly known as Websites. Some of the known feature includes

  • They run .Net, node.js, Java,php and even python
  • Web jobs for long running tasks, scheduled tasks
  • Integrated VS publish and remote debugging
  • Continous Intengrations with github, bitbucket, and Visual Studio Online
  • Auto-load balance and auto scale
  • Virtual networking and hybrid connections
  • Site slots for staged deployments

In azure portal all of your existing websites instances are now web apps in app service. Web hosting plan is now app service plan, and an app service plan can host any app type of app service e.g Web, Mobile, Logic or API Apps.

Mobile Apps

Formerly mobile services, and mobile services continue to be available as a stand alone service and remain fully supported as of this writing. Mobile app intengrates all of the functionality of Mobile Services and they include the following features.

  • Web jobs for long running tasks
  • CI with github, bitbucket, VSO
  • Auto-load balance auto scale GEO DR
  • Virtual networking and hybrid connections
  • Site slots for staged deployments
  • Supports single sign-On from various identity providers like facebook, google, microsoft account, twitter Azure AD
  • Offline sync which helps improve app responsiveness by caching server data locally on the device, make the app more resilient against network issues and syncing data across multiple devices helping solve any conflicts on the same record from different devices.
  • Push notifications via scalable push notitication engine, you can send personalized push notification however you want it addressed.
  • Easy connection to SaaS APIs.

Logic Apps.

This brings automation as a service by bringing new application for easy automation both with cloud and on premises systems. Some of its features includes:

  • Visually create business processes and workflows
  • There are a number of  pre-built templates to get started
  • Out of box support for popular SaaS and on premise applications
  • You can create you custom logic apps
  • There are biztalk APIs for expert integration scenario

That was just for introduction there is more information to come on the same.

As always happy coding 🙂

Implementing Entity Tag in ASP.NET Web API

Entity tags are a way of incorporating caching into the http protocol. When a server returns the response it attached a unique identifier (ETag) to the response back to the client, which represents the state of the object. So when the client makes a request for the same response, it will send the ETag in its request using the If-None-Match header and the server will use to determine whether to send a new response or response with a 304 (Not modified response which the gives the client a go ahead to use the local cache copy) The main advantage for this is to save the bandwidth since if the response has not changed there is no need to resend the same response as before. In this article we will implement ETag using action filter and so we will extend ActionFilterAttribute. Here is the full implementation

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebAPIETag.Models
public class EnableETag : ActionFilterAttribute
//This could be from a network source e.g database
private static ConcurrentDictionary<string, EntityTagHeaderValue> _etTagHeaderValues =
new ConcurrentDictionary<string, EntityTagHeaderValue>();

public override void OnActionExecuting(HttpActionContext actionContext)
//Get the request
var request = actionContext.Request;
if (request.Method == HttpMethod.Get)
var key = GetKey(request);

//Get if If-None match header
ICollection clientEtags = request.Headers.IfNoneMatch;

if (clientEtags.Count > 0)
EntityTagHeaderValue etag = null;
if (_etTagHeaderValues.TryGetValue(key, out etag) && clientEtags.Any(t => t.Tag == etag.Tag))
actionContext.Response = new HttpResponseMessage(HttpStatusCode.NotModified);

private void SetCacheControl(HttpResponseMessage httpResponseMessage)
httpResponseMessage.Headers.CacheControl = new CacheControlHeaderValue()
MaxAge = TimeSpan.FromSeconds(6),
MustRevalidate = true,
Private = true

private string GetKey(HttpRequestMessage request)
return request.RequestUri.ToString();

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
var request = actionExecutedContext.Request;
var key = GetKey(request);

EntityTagHeaderValue entityTag;

if (!_etTagHeaderValues.TryGetValue(key, out entityTag) || request.Method == HttpMethod.Post || request.Method == HttpMethod.Post)
entityTag = new EntityTagHeaderValue("\"" + Guid.NewGuid().ToString() + "\"");
_etTagHeaderValues.AddOrUpdate(key, entityTag, (k, val) => entityTag);

actionExecutedContext.Response.Headers.ETag = entityTag;

And this is how you apply the filter to the actions

public Order Get(int id)
return new Order
Id = "One",
OrderDate = DateTime.Now,
Owner = "Joe Doe"

On the index.cshtml we have

<div id="body">
<input id="details" type="button" value="Details" />
<ul id="orders" />
<ul id="employee" />

@section scripts{
<script type="text/javascript">
$(document).ready(function () {

$('#details').click(function () {
$.getJSON("/api/Order/12345", function (order) {
var now = new Date();
var ts = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
var content = order.Id + ' ' + order.Owner;
content = content + ' ' + order.OrderDate + ' ' + ts;
$('#orders').append($('<li/>', { text: content }));

You will now notice that once a request is sent, the result are cached on the client for 6 seconds. But after 6 seconds the cache expires and a new request is sent to the server. And since the result has not been modified since the last request, the response is 304.

In the initial request you will see this in the response headers


And in the consequent request for the same resource then the request header will include:


NB: The value might change since I am using guid for this

Of  importance to note are the two functions override
-OnActionExecuting: This runs before the action and looks for an Etag in the if-none-match header. If the header is present it is compared to check if it exists in the dictionary, and if  it matches then a 304 is sent back
-OnActionExecuted: runs after the action method. If the HTTP POST or a PUT method is used, then a new ETag is issued and gets stored in the dictionary and gets sent in the ETag header

Happy coding!!!

Comments are highly appreciated and lets meet here again…:)

%d bloggers like this: