• Hosting a WebAPI service on Windows Azure Web Sites

    by  • June 29, 2012 • USCloud, Windows Azure

    I was recently asked if it was possible to host a web service on Web Sites. I responded :

    “Well, anything IIS can do, Web Sites can do, so Yes.”

    We went back and forth a bit on what technology they were using (web services, WCF, etc.) and found out they wanted an interoperable rest service for mobile and tablet clients to consume.

    If you are working in .NET, and you want a REST service, WebAPI is the way to go. And yes, Web Sites can host it.

    So how about a sample?

    To do this sample you will need a trial account for Windows Azure that will let you use the new Web Sites feature that is in preview. You will also need VS2010 with the WebAPI package from NuGet, or VS2012 (which has WebAPI built in.)

    Start a new project (oh, I love the smell of a new project), and choose the web selection of templates. Choose the ASP.NET MVC4 Web Application template. Of course we need to name our project. It seems like projects can’t get anywhere without a name; it lends a certain certainness to them.

    image

    On the next popup you will have to pick what type of MVC project you would like to create. Go ahead and select the WebAPI, since that is what we are all here for. The view engine selection won’t matter, and only real men write code without tests. Then click OK.

    This will create an empty MVC WebAPI project that isn’t empty. It will include two controllers. The first is the Main controller, which gives you the standard MVC landing page, and the Value controller which is a sample WebAPI controller. You can keep that if you want, but I am going to deploy a service that reverses strings.

    What I found out a few years ago, while Chris and I were writing our book “Azure in Action,” that the market is crowed with calculator services, and that customers needing strings reversed was an underserved market that was ripe for disruption.

    Want to get an investor’s attention? Tell them you are disrupting the market.

    The Business End

    I added a class to the Models folder called ReverseString.cs. This includes some very innovative string reversal code (patent pending). We are going to call this from our service.

    * MVC purists will say to not put it in the model folder. Bah! This is quick demo, get over it! *

    image

    Right click on the controllers folder, and select add new…controller. This will create an empty controller for you. Select a name that makes sense for you, in this case I entered ‘reverser’. This will be part of the URL that people will call for your REST service. For example, the url will be: sample.com/api/reverser/stringtochange

    The ‘api’ component is a convention that is built into the template, because people are likely to mix MVC web apps and WebAPI stuff in the same project. If it really bugs you, you can change it in the api route configuration, but I am leaving it for now.

    The next portion, “reverser”, is the name of our controller. This is just how the normal MVC route works.

    The last portion of the URL is the parameter (named ID by the default api route) that will be passed into my Get method.

    The sample URL above should return egnahcotgnirts as a response.

    The Controller of the API

    If we look in the newly created controller, there are several template methods provided for us. These are the standard actions (nerds say verbs) that HTTP has as a protocol. Remember, true REST is about using HTTP at the application layer, and not as a dump truck for higher level abstractions (such as WS-* web services), so we want to use these verbs natively.

    In the standard template we have Get, Get with a parameter, Put, Post, and Delete. WebAPI automatically maps the http verb to the name of the action method name. You can override this if you want by decorating your actions with metatags. I have had enough ‘meta’ today (long story) so we are going to continue with the convention.

    Remove all the action methods, and replace it with these two:

    image

    The first Get method is used when there isn’t a parameter passed through the {id} of the URL. In this case, in the string reversal industry, that doesn’t do anything. We need a string to work on, so we are going to respond with “not implemented,” and charge the customer anyway. We should probably respond with a native HTTP error, in this case 502, but there is a thunder storm brewing outside, and I want to get this done before my battery dies on my laptop. Smile

    The second action method, takes that {id} from the URL, and returns a string. In this action we are simply going to call our model class ReverseStringTools, and return the results. That’s it. No opening HTTP ports, scrubbing JSON, nothing.

    WebAPI will automatically negotiate the response format with the client. For example, IE prefers JSON, so it will respond with JSON. Other browsers and clients may request other formats (Firefox I believe prefers XML).

    When you f5 this project, the browser will open. Add ‘/api/reverse/howdy’ to the URL in the browser, and IE will want to open a JSON file. Just open it with notepad, and you will see the response.

    If I have time later I can blog quickly about how to use Fiddler to call your APIs instead of the browser and notepad.

    Here is the URL in the browser and the notepad for those of you who are reading along and lazily not doing-along.

    image

    Our service is working. Let’s deploy it to Windows Azure Web Sites and start making CRAZY money!

    “!duolC ehT oT”

    Open up the Windows Azure management portal at http://manage.windowsazure.com. Click on the giant plus sign at the bottom and select web sites, and then Quick Create. Provide a name for your web site and click Create Web Site.

    image

    Your web site URL will now be (as in this picture) stringdemo.azurewebsites.net. Remember, you get 10 free web sites, so go crazy!

    Once the site is setup, which takes about 32 seconds, you will be on the dashboard for your site. On the right side, under the heading ‘Quick Glance’, click on the link “Download Publish Profile.” This will download a file that will configure Visual Studio to know how to communicate with Windows Azure and deploy your app.

    image

    Deploy the Bitz’es

    Now that you have downloaded the publish profile, head back to our old friend Visual Studio. Right click on your project and choose “Publish”. You will have to import the file you just downloaded on the first page of the wizard. We don’t want to bother ourselves with the other options, so just go crazy and click Publish.

    Visual Studio will build and the deploy your web app to your web site. This may take time, depending how big your solution is, but will usually only take a moment of two. Once the big VS is done, it will open a browser to your app. Feel free to make an API call to test it.

    image

    See? It works just fine, and only takes a few minutes. Have fun.

    You can grab the source here: http://sdrv.ms/LVigkM

    About

    Brian H. Prince is the Chief Technical Cloud Evangelist for Microsoft, based in the US. He gets super excited whenever he talks about technology, especially cloud computing, patterns, and practices. His job is to help customers strategically leverage technology, and help them bring their architecture to a super level. In a past life Brian was a part of super startups, super marketing firms, and super consulting firms. Much of his super architecture background includes building super scalable applications, application integration, and award winning web applications. All of them were super. Further, he is a co-founder of the non-profit organization CodeMash (www.codemash.org). He speaks at various international technology conferences. He only wishes his job didn’t require him to say ‘super’ so much. Brian is the co-author of “Azure in Action”, published by Manning Press. Brian holds a Bachelor of Arts degree in Computer Science and Physics from Capital University, Columbus, Ohio. He is also a zealous gamer. For example, he is a huge fan of Fallout 3, Portal, and pretty much every other game he plays.