Saturday, October 5, 2013

an example of handing an object to an ASP.NET Web API ApiController from jQuery

Just give a blob of JSON like so:

<script src="/Scripts/jquery-1.8.2.js"></script>
<script language="javascript">
   $(function () {
      myAsynchronousThing();
   });
   function myAsynchronousThing() {
      $.ajax({
         type: "POST",
         url: '/api/PET/',
         dataType: 'json',
         data: {
            Fleas: 42
         },
         success: function (result) {
            alert(result);
         }
      });
   }
</script>

 
 

Here is my ApiController. Note, that a method for a verb does not need to be explicitly named for the verb, it just needs to have a name that STARTS with the explicit name for the verb. I had sort of hoped I could overload the methods in an ApiController and have two POST methods, one for a Dog and one for a Cat, but it does not seem I may do so.

using System.Web.Http;
using WebApiExperiment.Models;
namespace WebApiExperiment.Controllers
{
   public class PetController : ApiController
   {
      public string PostDog(Dog dog)
      {
         return "My dog has fleas! (" + dog.Fleas + ")";
      }
   }
}

 
 

Here is my Dog:

namespace WebApiExperiment.Models
{
   public class Dog
   {
      public int Fleas { get; set; }
   }
}

 
 

I am starting to read a book on security for the ASP.NET Web API. One of the things in the book is a shocking (I'm kidding) suggestion that the verb methods should do things that correspond to their designations in ApiControllers for various objects with regards to CRUD functionality. In a Dog-themed ApiController, the Delete method would destroy a Dog record and the Get method would get one or many. I was surprised to see Put slated for updates and Post slated for creates as Put is idempotent. I suppose one may sanity check a create to see if a record already exists upon a create act, but there is not really a comparable way of preventing duplicate updates. I suppose it makes sense.

No comments:

Post a Comment