Sunday, June 17, 2012

I saw Shawn Weisfeld's talk on ASP.NET Web API eight days ago.

@shawnweisfeld is speaking on ASP.NET Web API at #austincodecamp on Twitpic

ASP.NET Web API and getting started with it were made to seem easy by Shawn Weisfeld at a talk he gave eight days ago. This was the best of several talks I saw at Code Camp. Note: I already had MVC4, but I had to install it anew to get the Web API Project Template. I guess I had an older version of the MVC4 Beta. To reinstall MVC4 I clicked on the link which read "ASP.NET MVC 4 RC for Visual Studio 2010 SP1" here. Hey, that is a good hint towards how to spin up a Web API app: First, make a MVC4 project and, second, pick the Web API template. These are the two wizard steps one should undertake after selecting "Project..." from the "New" menu from within the "File" menu from within Visual Studio 2010. This post will offer another of the goofy calculator examples I am so fond of. I put this HTML in the Index.cshtml view for the HomeController in a new project:

The square of <input type="text" id="number" value="3" style="width: 20px;" /> is...
<div id="calcuation" style="font-size: 40px;">9</div>
<button id="button">Update</button>

 
 

The square of is...
9

 
 

OK, here we go! In the Controllers folder one will notice ValuesController which inheirts from ApiController instead of Controller! It's default code is like so:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;

using System.Web.Http;
   
namespace MvcApplication1.Controllers
{
   public class ValuesController : ApiController
   {
      
// GET api/values
      public IEnumerable Get()
      {
         return new string[] { "value1", "value2" };
      }
   
      
// GET api/values/5
      public string Get(int id)
      {
         return "value";
      }
   
      
// POST api/values
      public void Post(string value)
      {
      }
   
      
// PUT api/values/5
      public void Put(int id, string value)
      {
      }
   
      
// DELETE api/values/5
      public void Delete(int id)
      {
      }
   }
}

 
 

I changed the Post method like so:

public HttpResponseMessage Post(string value)
{
   decimal number = Convert.ToDecimal(value);
   value = (number*number).ToString();
   return this.Request.CreateResponse<string>(HttpStatusCode.Created, value);
}

 
 

I then put this blob of jQuery into Index.cshtml and had a working calculator:

<script src="/Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script type="text/javascript">
   $(function () {
      $('#button').bind('click', function () {
         var userinput = $('#number').val();
         $.ajax({
            type: 'POST',
            url: '/api/Values?value=' + userinput,
            statusCode: {
               201: function (value) {
                  document.getElementById('calcuation').innerHTML = value;
               }
            }
         });
      });
   });
</script>

 
 

Let me also mention:

  1. For starters, what about error handling? What if one hands in a letter instead of a number in this scenario? Well, in Shawn's demo he suggested that errors should be handled on the client side. Just as my code offers a to-do for status code 201, it could comparably offer a to-do for errors. I tried to append a 400 scenario to my own code to catch the problem but it doesn't work (at least not in Cassini testing). It could be that 400 is just the wrong status code. I suppose I should look at this and study up. Ugh, I'm going to have to learn what the status codes are to use ASP.NET Web API! :P
    this is how @shawnweisfeld addresses ASP.NET Web API errors on Twitpic
  2. By default ASP.NET Web API uses JSON. One may specify XML instead or roll one's own format. At http://bit.ly/A6ybsy, Headspring's Pedro Reys has a blog posting on this. Something Shawn called a “Formatter” delineates what format is used. Again, JSON is the default.
  3. ASP.NET Web API exists so that one may escape XML-heavy WCF in lieu of a HTTP requests-favored interface. Shawn recommended using Fiddler to inspect HTTP traffic.

2 comments:

  1. just posted the recording of the talk on UserGroup.tv http://usergroup.tv/videos/asp-net-web-api

    ReplyDelete