Saturday, December 12, 2015

Spec an extra chunk of a route when hitting the Web API!

Alright, open Visual Studio 2015 and make a generic application which mixes MVC and the Web API. Quickly, set up the CORS stuff as suggested here and then rewrite the default "home page" view to look like this:

@{
   string fullLocation = HttpContext.Current.Request.Url.ToString();
   ViewBag.LocaleParts = fullLocation.Split("/".ToCharArray());
}
<script src="/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
   $(function () {
      var url = "http://";
      url = url + "@ViewBag.LocaleParts[2]";
      url = url + "/Api/Whatever/Foo";
      $.ajax({
         type: "POST",
         url: url,
         dataType: 'json',
         data: {Bar:'Baz'},
         success: function () {
            console.log('yay :)');
         },
         error: function () {
            console.log('nay :(');
         }
      });
   });
</script>

 
 

Clearly, we are trying to hand an API endpoint at "Whatever" two bits of data in two different ways. We are trying to pass in "Foo" as a chunk of the URL and we are trying to pass "Baz" as a setting on a JSON object. This is all doable. The "Whatever" Web API controller looks like this:

using System.Web.Http;
using System.Web.Http.Cors;
using SomethingSimple.Models;
namespace SomethingSimple.Controllers
{
   [EnableCors(origins: "*", headers: "*", methods: "*")]
   public class WhateverController : ApiController
   {
      public void Post(string id, Qux qux)
      {
         var breakpoint = "OK";
      }
   }
}

 
 

If we set a breakpoint at the line of code in the controller which has "OK" in it (and which does nothing whatsoever in and of itself) and we debug the application with the debugger, we ought to be able to hit the breakpoint and inspect both the "id" and "qux" variables. The first variable holds "Foo" and the second holds an instance of Qux with the Bar property set to "Baz" as desired. My Qux class looks like this:

namespace SomethingSimple.Models
{
   public class Qux
   {
      public string Bar { get; set; }
   }
}

No comments:

Post a Comment