Implementing REST service using WebAPI v2 hosted in WorkerRole
As I wrote in the previous blog post, I spent some time comparing WCF and WebAPI as a frameworks for building the services and deploying them into Azure.
Just to recap, our goal is to build a sample REST service, in this post, using WCF hosted in Azure.
In this blog post I'll describe how to build a sample app using ASP.NET WebAPI 2 technology stack.
Initial setup
- Run Visual Studio under the administrator in order to use full emulator
- Ensure that you have the Azure SKD 2.2
- Install nuget package WebAPI v2 Core
- Install nuget package Microsoft.AspNet.WebApi.Owin
- Install nuget package Microsoft.Owin
- Install nuget package Microsoft.Owin.Host.HttpListener
- Install nuget package Microsoft.Owin.Hosting
- Create a cloud service project with worker role WebAPIDemoWorkerRole
Define a contract
Define contract with the its implementation within API controller
The great thing is that WebAPI is built with convention over configuration mindset ;) More information can be found here
Self-host the service (API controller)
Add a startup class and use WebAPI.
Selfhost the WebAPI server in the worker role
Learned from the previous post, we need to open the port and run the service in the elevated permissions.
Selhost WebAPI in the worker role using startup configuration.
I like that the configuration is defined separately out of the worker start task (separation of concerns). In addition, WebAPI enables to have a complete control over routes and instead of defining the routing rules, it's possible to use routing via attributes, which rocks!
That's all. Now, it's possible to run it locally via emulator as well as deploy it to the Azure.