Thursday, October 23, 2014

Send a header within a jQuery .ajax implementation.

If you click the button in this view, it will put "my dog has fleas" into the token div.

<button id="clickhere">click here</button>
<div id="response"></div>
@section scripts
{
   <script language="javascript">
      $('#clickhere').bind("click", function() {
         $.ajax({
            type: "POST",
            url: "/api/values",
            headers: { 'possessions': 'fleas' },
            success: function (result) {
               $("#response").html(result);
            }
         });
      });
   </script>
}

 
 

At the Web API side in C# the way to make sense of the header looks like this:

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace Stuff.Controllers
{
   public class ValuesController : ApiController
   {
      public string Post()
      {
         IEnumerable<string> headerValues;
         if (Request.Headers.TryGetValues("possessions", out headerValues))
         {
            return "my dog has " + headerValues.First();
         }
         return "my dog has nada";
      }
   }
}

No comments:

Post a Comment