Delivering solid user friendly software solutions since the dawn of time.

MVC4 Fundamentals and the WebApi - Notes

Categories: Notes WebApi
MVC4 Fundamentals and the WebApi
Scott Allen

I only looked at this module of the course. John Papa referred to it in his single page application course. Not much new except if you didn't know about curl and handlebars.

  • System.Web.Http
  • System.Web.Http.WebHost
  • GET, POST, PUT, DELETE by default
  • [AcceptVerbs] for others

Scott preferes using a plural name. Eg. VideosController

  • curl http://somewebsite/api/videos
  • curl http://somewebsite/api/videos -X GET
  • curl http://somewebsite/api/videos -X DELETE

-> File not found exception, then IIS needs to be configured

-> IISExpress applicationhost file add on ExtentionlessUrl the verbs

  • curl http://somewebsite/api/videos -X GET -v
  • curl http://somewebsite/api/videos -X GET -H "Accept: application/json"
  • curl http://somewebsite/api/videos -X POST -d "value=scott"
  • curl http://somewebsite/api/videos -X POST -d "=scott"
Content negotiation
  • Same resource can have multiple representations.
  • Accept: image/png
  • Accept: Text/html 
Action Parameters
  • Primitive types assumed to not be in the message body, unless public void Post([FromBody]string value) {}
  • Complex types assumed in the message body
  • Only a  single model allowed from the message body
EF NuGet 
  • enable-migrations
  • Seed(... AddOrUpdate( ) )
  • update-database
  • db.Configuration.ProxyCreationEnabled = false;
Showing Data in view
  • Update-Package jQuery
  • Update-Package HandleBars
  • <script> type attribute is no longer needed in Html5

var videoApiUrl = '@Url.RouteUrl("DefaultApi", new { httproute="" , ... '

//global error handler

$(document).ajaxError(function (event, xhr) {

alert(xhr.status + ":" + xhr.statusText);


<script id="template" type="text/html>

{{#each video}}





public Video GetVideo(int id)


   var video =  db.Find(id); 

   if (video==null)


     throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));


   return video;


public HttpResponseMessage PutVideo(int id, Video video)


   db.Entry(video).State = EntityState.Modified;

.. HttpStatus NotFound OK BadRequest


On post set 201 Created and add response.Headers.Location

On Delete check for DbUpdateConcurrencyException

install-package Microsoft.AspNet.WebApi.Client

var client = new HttpClient();


   new MediaTypeWithQualityHeaderValue("application/xml"));

var result = client.GetAsync(new Uri(...))