SlideShare a Scribd company logo
ASP.NET WEB API

          @thangchung
           08-08-2012
Agenda
•   A model of restful maturity
•   ASP.NET Web API
•   Mapping from WCF to Web API
•   Integrated stack supporting features
•   What we do in BC Survey project
A model of restful maturity
• Restful coined by Roy Thomas Fielding in his
  dissesertation (2000)
• A model of restful maturity introduced by
  Leonard Richardson (2008)
• The glory of REST by Martin Fowler (2010)
• We have 4 levels of maturity
  –   Level 0: The swamp of POX (Plain Old XML)
  –   Level 1: Resources
  –   Level 2: HTTP verbs
  –   Level 3: Hypermedia Controls
ASP.NET WEB API
Level 0: The swamp of POX
• Use RPC (Remote Procedure Invocation)




• POST /appointmentService HTTP/1.1 [various
  other headers]
     <openSlotRequest date = "2010-01-04" doctor =
          "mjones"/>
• The server return an open slot list as
   HTTP/1.1 200 OK [various headers]
      <openSlotList>
       <slot start = "1400" end = "1450">
             <doctor id = “mjones”/>
       </slot>
       <slot start = "1600" end = "1650">
             <doctor id = “mjones”/>
       </slot>
     </openSlotList>
• We choose the the first item and send it to server:
   POST /appointmentService HTTP/1.1 [various other headers]
      <appointmentRequest>
             <slot doctor = "mjones" start = "1400" end =
                     "1450"/>
             <patient id = "jsmith"/>
      </appointmentRequest>
• The server accept this request and register
  name of patient
  HTTP/1.1 200 OK [various headers]
     <appointment>
      <slot doctor = "mjones" start = "1400" end = "1450"/>
      <patient id = "jsmith"/>
     </appointment>
• If some thing wrong, the result should be
  HTTP/1.1 200 OK [various headers]
  <appointmentRequestFailure>
     <slot doctor = "mjones" start = "1400" end = "1450"/>
     <patient id = "jsmith"/>
     <reason>Slot not available</reason>
     </appointmentRequestFailure>
Level 1: Resources
• POST /doctors/mjones HTTP/1.1 [various
  other headers]
  <openSlotRequest date = "2010-01-04"/>
• HTTP/1.1 200 OK [various headers]
  <openSlotList>
   <slot id = "1234" doctor = "mjones" start = "1400"
            end = "1450"/>
   <slot id = "5678" doctor = "mjones" start = "1600"
            end = "1650"/>
  </openSlotList>
• POST /slots/1234 HTTP/1.1 [various other
  headers]
  <appointmentRequest>
     <patient id = "jsmith"/>
  </appointmentRequest>
• HTTP/1.1 200 OK [various headers]
  <appointment>
   <slot id = "1234" doctor = "mjones" start = "1400"
     end = "1450"/>
   <patient id = "jsmith"/>
  </appointment>
• The link at the moment should be like this
  – http://royalhope.nhs.uk/slots/1234/appointment
Level 2: HTTP Verbs
• GET/POST/PUT/DELETE
• Use GET
 /doctors/mjones/slots?date=20100104&status=open
  HTTP/1.1 Host: royalhope.nhs.uk
• HTTP/1.1 200 OK [various headers]
  <openSlotList>
     <slot id = "1234" doctor = "mjones" start = "1400"
            end = "1450"/>
     <slot id = "5678" doctor = "mjones" start = "1600"
            end = "1650"/>
  </openSlotList>
• POST /slots/1234 HTTP/1.1 [various other
  headers]
  <appointmentRequest>
     <patient id = "jsmith"/>
  </appointmentRequest>
• HTTP/1.1 201 Created Location:
  slots/1234/appointment [various headers]
  <appointment>
     <slot id = "1234" doctor = "mjones" start =
            "1400" end = "1450"/>
     <patient id = "jsmith"/>
  </appointment>
• If something wrong when we use POST to
  server, the result should be
  HTTP/1.1 409 Conflict [various headers]
  <openSlotList>
     <slot id = "5678" doctor = "mjones" start =
            "1600" end = "1650"/>
  </openSlotList>
• Benefits:
  – Caching on GET request (natural capability with
    HTTP protocol)
Level 3: Hypermedia Controls
• HATEOAS (Hypertext As The Engine Of
  Application State)
• GET
  /doctors/mjones/slots?date=20100104&status=o
  pen HTTP/1.1 Host: royalhope.nhs.uk
• HTTP/1.1 200 OK [various headers]
  <openSlotList>
     <slot id = "1234" doctor = "mjones" start = "1400"
             end = "1450">
      <link rel = "/linkrels/slot/book" uri =
             "/slots/1234"/>
     </slot>
     <slot id = "5678" doctor = "mjones" start = "1600"
             end = "1650">
      <link rel = "/linkrels/slot/book" uri =
             "/slots/5678"/>
     </slot>
  </openSlotList>
• POST /slots/1234 HTTP/1.1 [various other
  headers]
  <appointmentRequest>
     <patient id = "jsmith"/>
  </appointmentRequest>
• HTTP/1.1 201 Created Location:
   http://royalhope.nhs.uk/slots/1234/appointment [various headers]
  <appointment>
   <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/>
        <patient id = "jsmith"/>
        <link rel = "/linkrels/appointment/cancel" uri =
                  "/slots/1234/appointment"/>
        <link rel = "/linkrels/appointment/addTest" uri =
                  "/slots/1234/appointment/tests"/>
        <link rel = "self" uri = "/slots/1234/appointment"/>
        <link rel = "/linkrels/appointment/changeTime" uri =
"/doctors/mjones/slots?date=20100104@status=open"/>
        <link rel = "/linkrels/appointment/updateContactInfo" uri =
"/patients/jsmith/contactInfo"/>
        <link rel = "/linkrels/help" uri = "/help/appointment"/>
  </appointment>


• What’s benefit of those?
ASP.NET Web API
• What is the purpose of the WebAPIs?
• Why do we need REST HTTP services? What’s
  wrong with SOAP-over-HTTP?
• Why did the WebAPIs move from WCF to
  ASP.NET MVC?
• Is there still a use for WCF? When should I
  choose Web APIs over WCF?
Mapping from WCF to Web API
•   WCF Web AP -> ASP.NET Web API
•   Service -> Web API controller
•   Operation -> Action
•   Service contract -> Not applicable
•   Endpoint -> Not applicable
•   URI templates -> ASP.NET Routing
•   Message handlers -> Same
•   Formatters -> Same
•   Operation handlers -> Filters, model binders
Integrated stack supporting features
• Modern HTTP programming model
• Full support for ASP.NET Routing
• Content negotiation and custom formatters
• Model binding and validation
• Filters
• Query composition
• Easy to unit test
• Improved Inversion of Control (IoC) via
  DependencyResolver
• Code-based configuration
• Self-host
What we do in BC Survey project
•   Introduced Web API service
•   Web API routing and actions
•   Working with HTTP (Verb & return status)
•   Format & model binding
•   Dependency Resolver with Autofac
•   Web API clients
•   Host ASP.NET Web API on IIS
Web API service
public class SurveyAPIController : BaseApiController
{
  // GET api/Survey
  [Queryable]
  public IQueryable<SurveyDTO> Get()          {
    return _surveyAppService.GetAllSurvey().AsQueryable();
  }
  // GET api/Survey/5
  public SurveyDTO Get(int id) { … }
    // POST api/Survey
    public HttpResponseMessage Post(SurveyDTO value) { … }
    // PUT api/Survey/5
    public HttpResponseMessage Put(int id, SurveyDTO value) { … }
    // DELETE api/Survey/5
    public HttpResponseMessage Delete(int id) {… }
}
Web API service
• OData (Open data protocol): The Open Data
  Protocol is an open web protocol for querying
  and updating data. The protocol allows for a
  consumer to query a datasource over the
  HTTP protocol and get the result back in
  formats like Atom, JSON or plain XML,
  including pagination, ordering or filtering of
  the data.
Web API routing and actions
• routes.MapHttpRoute("DefaultApi",
      "api/{controller}/{id}", new { id =
      RouteParameter.Optional });
MapHttpRoute really different from default
routing in ASP.NET MVC
• routes.MapRoute("Default",
      "{controller}/{action}/{id}", new {
      controller = "Home", action = "Index", id =
      UrlParameter.Optional });
Working with HTTP (Verb & return
                status)
• It have 9 method definitions like
   –   GET
   –   HEAD
   –   POST
   –   PUT
   –   DELETE
   –   TRACE
   –   CONNECT
• We can reference more at
  http://www.w3.org/Protocols/rfc2616/rfc2616-
  sec9.html
Working with HTTP (Verb & return
                  status)
•   200 OK
•   201 Created
•   400 Bad Request
•   401 Unauthorized
•   404 Not Found
•   409 Conflict
•   500 Internal Server Error
•   501 Not Implemented
•   Reference more at
    http://en.wikipedia.org/wiki/List_of_HTTP_status_cod
    es
Format & model binding
• Media-Type Formatters
     // Remove the XML formatter
     config.Formatters.Remove(config.Formatters.XmlF
            ormatter);
     var json = config.Formatters.JsonFormatter;
     json.SerializerSettings.DateFormatHandling =
            DateFormatHandling.MicrosoftDateFormat;
     json.SerializerSettings.Formatting =
            Formatting.Indented;
• Content Negotiation
• Model Validation in ASP.NET Web API
Dependency Resolver with Autofac
var builder = new ContainerBuilder();
 // register autofac modules
builder.RegisterModule<WebModule>();
builder.RegisterModule<DataSurveyModule>();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterFilterProvider();

var container = builder.Build();
DependencyResolver.SetResolver(new
AutofacDependencyResolver(container));
Q&A
References
• http://www.ics.uci.edu/~fielding/pubs/dissert
  ation/top.htm
• http://www.crummy.com/writing/speaking/2
  008-QCon/act3.html
• http://martinfowler.com/articles/richardsonM
  aturityModel.html
• http://www.asp.net/web-api/

More Related Content

What's hot (20)

PPT
Java Servlets
BG Java EE Course
 
PPTX
ASP.NET Web API
habib_786
 
PPTX
Servlets
ZainabNoorGul
 
PDF
Diagramas Analisis
innovalabcun
 
PPT
Developing an ASP.NET Web Application
Rishi Kothari
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PDF
11 Curso de POO en java - métodos constructores y toString()
Clara Patricia Avella Ibañez
 
PPT
ENTRADA Y SALIDA DE DATOS EN JAVA
Gabriel Suarez
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPTX
Java con base de datos
Vicente Alberca
 
PDF
Uso de Excepciones en JAVA
innovalabcun
 
PDF
Clases y objetos de java
innovalabcun
 
PPT
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
PPT
SQL Queries
Nilt1234
 
PPTX
Antecedentes de la tgs
julianj
 
PDF
Consultas básicas en sql server
Rodrigo Alfaro Pinto
 
PPTX
Classes objects in java
Madishetty Prathibha
 
PPTX
Data types in php
ilakkiya
 
PPTX
Sql subquery
Raveena Thakur
 
Java Servlets
BG Java EE Course
 
ASP.NET Web API
habib_786
 
Servlets
ZainabNoorGul
 
Diagramas Analisis
innovalabcun
 
Developing an ASP.NET Web Application
Rishi Kothari
 
Java 8 Lambda Expressions
Scott Leberknight
 
11 Curso de POO en java - métodos constructores y toString()
Clara Patricia Avella Ibañez
 
ENTRADA Y SALIDA DE DATOS EN JAVA
Gabriel Suarez
 
Java exception handling
BHUVIJAYAVELU
 
Java con base de datos
Vicente Alberca
 
Uso de Excepciones en JAVA
innovalabcun
 
Clases y objetos de java
innovalabcun
 
MYSQL - PHP Database Connectivity
V.V.Vanniaperumal College for Women
 
SQL Queries
Nilt1234
 
Antecedentes de la tgs
julianj
 
Consultas básicas en sql server
Rodrigo Alfaro Pinto
 
Classes objects in java
Madishetty Prathibha
 
Data types in php
ilakkiya
 
Sql subquery
Raveena Thakur
 

Viewers also liked (20)

PDF
C# ASP.NET WEB API APPLICATION DEVELOPMENT
Dr. Awase Khirni Syed
 
PPTX
ASP.NET Mvc 4 web api
Tiago Knoch
 
PPTX
The ASP.NET Web API for Beginners
Kevin Hazzard
 
PPTX
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
 
PPTX
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj
 
PPTX
Web API or WCF - An Architectural Comparison
Adnan Masood
 
PPT
Excellent rest using asp.net web api
Maurice De Beijer [MVP]
 
DOC
WCF tutorial
Abhi Arya
 
PPT
Introduction to the Web API
Brad Genereaux
 
PPTX
The Full Power of ASP.NET Web API
Eyal Vardi
 
PPTX
RESTful API Design Best Practices Using ASP.NET Web API
💻 Spencer Schneidenbach
 
PPTX
Introduction to asp.net web api
Lohith Goudagere Nagaraj
 
PPTX
Secure Coding for NodeJS
Thang Chung
 
PDF
Passport Nodejs Lightening Talk
Kianosh Pourian
 
PDF
ASP.NET Core 1 for MVC- and WebAPI-Devs
Manfred Steyer
 
PPTX
Web 2.0 y nube de internet
Johanna Alexandra Cuaspud Cuchala
 
PDF
ASP.NET - Architecting single page applications with knockout.js
Dimitar Danailov
 
PPTX
Web Technologies
Lior Zamir
 
PDF
SQL - שפת הגדרת הנתונים
מורן אלקובי
 
PDF
אחסון מידע - ל-websql ו-indexdb רן בר-זיק
Israeli Internet Association technology committee
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
Dr. Awase Khirni Syed
 
ASP.NET Mvc 4 web api
Tiago Knoch
 
The ASP.NET Web API for Beginners
Kevin Hazzard
 
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
 
Overview of Rest Service and ASP.NET WEB API
Pankaj Bajaj
 
Web API or WCF - An Architectural Comparison
Adnan Masood
 
Excellent rest using asp.net web api
Maurice De Beijer [MVP]
 
WCF tutorial
Abhi Arya
 
Introduction to the Web API
Brad Genereaux
 
The Full Power of ASP.NET Web API
Eyal Vardi
 
RESTful API Design Best Practices Using ASP.NET Web API
💻 Spencer Schneidenbach
 
Introduction to asp.net web api
Lohith Goudagere Nagaraj
 
Secure Coding for NodeJS
Thang Chung
 
Passport Nodejs Lightening Talk
Kianosh Pourian
 
ASP.NET Core 1 for MVC- and WebAPI-Devs
Manfred Steyer
 
Web 2.0 y nube de internet
Johanna Alexandra Cuaspud Cuchala
 
ASP.NET - Architecting single page applications with knockout.js
Dimitar Danailov
 
Web Technologies
Lior Zamir
 
SQL - שפת הגדרת הנתונים
מורן אלקובי
 
אחסון מידע - ל-websql ו-indexdb רן בר-זיק
Israeli Internet Association technology committee
 
Ad

Similar to ASP.NET WEB API (20)

PPTX
Rest in practice
Gabor Torok
 
PPTX
REST and Web API
IT Weekend
 
PPTX
REST and Web API
Roman Kalita
 
PPTX
About REST. Архитектурные семинары Softengi
Softengi
 
PPTX
Webservices Overview : XML RPC, SOAP and REST
Pradeep Kumar
 
PPTX
Rest
Carol McDonald
 
PPTX
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
PDF
ERRest - Designing a good REST service
WO Community
 
PPTX
Spring Boot and REST API
07.pallav
 
PDF
Android App Development 06 : Network &amp; Web Services
Anuchit Chalothorn
 
PPT
RESTful services
gouthamrv
 
PPTX
Constraints Make You Sexy - What is Rest
anorqiu
 
PDF
Doing REST Right
Kerry Buckley
 
PDF
From unREST to REST
Anand Srinivasan
 
PDF
A Quick Introduction to YQL
Max Manders
 
PDF
Velocity EU 2014 — Offline-first web apps
andrewsmatt
 
PPTX
Boost Your Content Strategy for REST APIs with Gururaj BS
Information Development World
 
PDF
Introduction to rest using flask
Wekanta
 
PPTX
01. http basics v27
Eoin Keary
 
PDF
Java Servlets.pdf
Arumugam90
 
Rest in practice
Gabor Torok
 
REST and Web API
IT Weekend
 
REST and Web API
Roman Kalita
 
About REST. Архитектурные семинары Softengi
Softengi
 
Webservices Overview : XML RPC, SOAP and REST
Pradeep Kumar
 
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
ERRest - Designing a good REST service
WO Community
 
Spring Boot and REST API
07.pallav
 
Android App Development 06 : Network &amp; Web Services
Anuchit Chalothorn
 
RESTful services
gouthamrv
 
Constraints Make You Sexy - What is Rest
anorqiu
 
Doing REST Right
Kerry Buckley
 
From unREST to REST
Anand Srinivasan
 
A Quick Introduction to YQL
Max Manders
 
Velocity EU 2014 — Offline-first web apps
andrewsmatt
 
Boost Your Content Strategy for REST APIs with Gururaj BS
Information Development World
 
Introduction to rest using flask
Wekanta
 
01. http basics v27
Eoin Keary
 
Java Servlets.pdf
Arumugam90
 
Ad

Recently uploaded (20)

PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 

ASP.NET WEB API

  • 1. ASP.NET WEB API @thangchung 08-08-2012
  • 2. Agenda • A model of restful maturity • ASP.NET Web API • Mapping from WCF to Web API • Integrated stack supporting features • What we do in BC Survey project
  • 3. A model of restful maturity • Restful coined by Roy Thomas Fielding in his dissesertation (2000) • A model of restful maturity introduced by Leonard Richardson (2008) • The glory of REST by Martin Fowler (2010) • We have 4 levels of maturity – Level 0: The swamp of POX (Plain Old XML) – Level 1: Resources – Level 2: HTTP verbs – Level 3: Hypermedia Controls
  • 5. Level 0: The swamp of POX • Use RPC (Remote Procedure Invocation) • POST /appointmentService HTTP/1.1 [various other headers] <openSlotRequest date = "2010-01-04" doctor = "mjones"/>
  • 6. • The server return an open slot list as HTTP/1.1 200 OK [various headers] <openSlotList> <slot start = "1400" end = "1450"> <doctor id = “mjones”/> </slot> <slot start = "1600" end = "1650"> <doctor id = “mjones”/> </slot> </openSlotList> • We choose the the first item and send it to server: POST /appointmentService HTTP/1.1 [various other headers] <appointmentRequest> <slot doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointmentRequest>
  • 7. • The server accept this request and register name of patient HTTP/1.1 200 OK [various headers] <appointment> <slot doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointment> • If some thing wrong, the result should be HTTP/1.1 200 OK [various headers] <appointmentRequestFailure> <slot doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> <reason>Slot not available</reason> </appointmentRequestFailure>
  • 9. • POST /doctors/mjones HTTP/1.1 [various other headers] <openSlotRequest date = "2010-01-04"/> • HTTP/1.1 200 OK [various headers] <openSlotList> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"/> </openSlotList>
  • 10. • POST /slots/1234 HTTP/1.1 [various other headers] <appointmentRequest> <patient id = "jsmith"/> </appointmentRequest> • HTTP/1.1 200 OK [various headers] <appointment> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointment> • The link at the moment should be like this – http://royalhope.nhs.uk/slots/1234/appointment
  • 11. Level 2: HTTP Verbs • GET/POST/PUT/DELETE
  • 12. • Use GET /doctors/mjones/slots?date=20100104&status=open HTTP/1.1 Host: royalhope.nhs.uk • HTTP/1.1 200 OK [various headers] <openSlotList> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"/> </openSlotList>
  • 13. • POST /slots/1234 HTTP/1.1 [various other headers] <appointmentRequest> <patient id = "jsmith"/> </appointmentRequest> • HTTP/1.1 201 Created Location: slots/1234/appointment [various headers] <appointment> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> </appointment>
  • 14. • If something wrong when we use POST to server, the result should be HTTP/1.1 409 Conflict [various headers] <openSlotList> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"/> </openSlotList> • Benefits: – Caching on GET request (natural capability with HTTP protocol)
  • 15. Level 3: Hypermedia Controls • HATEOAS (Hypertext As The Engine Of Application State)
  • 16. • GET /doctors/mjones/slots?date=20100104&status=o pen HTTP/1.1 Host: royalhope.nhs.uk • HTTP/1.1 200 OK [various headers] <openSlotList> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"> <link rel = "/linkrels/slot/book" uri = "/slots/1234"/> </slot> <slot id = "5678" doctor = "mjones" start = "1600" end = "1650"> <link rel = "/linkrels/slot/book" uri = "/slots/5678"/> </slot> </openSlotList>
  • 17. • POST /slots/1234 HTTP/1.1 [various other headers] <appointmentRequest> <patient id = "jsmith"/> </appointmentRequest>
  • 18. • HTTP/1.1 201 Created Location: http://royalhope.nhs.uk/slots/1234/appointment [various headers] <appointment> <slot id = "1234" doctor = "mjones" start = "1400" end = "1450"/> <patient id = "jsmith"/> <link rel = "/linkrels/appointment/cancel" uri = "/slots/1234/appointment"/> <link rel = "/linkrels/appointment/addTest" uri = "/slots/1234/appointment/tests"/> <link rel = "self" uri = "/slots/1234/appointment"/> <link rel = "/linkrels/appointment/changeTime" uri = "/doctors/mjones/slots?date=20100104@status=open"/> <link rel = "/linkrels/appointment/updateContactInfo" uri = "/patients/jsmith/contactInfo"/> <link rel = "/linkrels/help" uri = "/help/appointment"/> </appointment> • What’s benefit of those?
  • 19. ASP.NET Web API • What is the purpose of the WebAPIs? • Why do we need REST HTTP services? What’s wrong with SOAP-over-HTTP? • Why did the WebAPIs move from WCF to ASP.NET MVC? • Is there still a use for WCF? When should I choose Web APIs over WCF?
  • 20. Mapping from WCF to Web API • WCF Web AP -> ASP.NET Web API • Service -> Web API controller • Operation -> Action • Service contract -> Not applicable • Endpoint -> Not applicable • URI templates -> ASP.NET Routing • Message handlers -> Same • Formatters -> Same • Operation handlers -> Filters, model binders
  • 21. Integrated stack supporting features • Modern HTTP programming model • Full support for ASP.NET Routing • Content negotiation and custom formatters • Model binding and validation • Filters • Query composition • Easy to unit test • Improved Inversion of Control (IoC) via DependencyResolver • Code-based configuration • Self-host
  • 22. What we do in BC Survey project • Introduced Web API service • Web API routing and actions • Working with HTTP (Verb & return status) • Format & model binding • Dependency Resolver with Autofac • Web API clients • Host ASP.NET Web API on IIS
  • 23. Web API service public class SurveyAPIController : BaseApiController { // GET api/Survey [Queryable] public IQueryable<SurveyDTO> Get() { return _surveyAppService.GetAllSurvey().AsQueryable(); } // GET api/Survey/5 public SurveyDTO Get(int id) { … } // POST api/Survey public HttpResponseMessage Post(SurveyDTO value) { … } // PUT api/Survey/5 public HttpResponseMessage Put(int id, SurveyDTO value) { … } // DELETE api/Survey/5 public HttpResponseMessage Delete(int id) {… } }
  • 24. Web API service • OData (Open data protocol): The Open Data Protocol is an open web protocol for querying and updating data. The protocol allows for a consumer to query a datasource over the HTTP protocol and get the result back in formats like Atom, JSON or plain XML, including pagination, ordering or filtering of the data.
  • 25. Web API routing and actions • routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); MapHttpRoute really different from default routing in ASP.NET MVC • routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
  • 26. Working with HTTP (Verb & return status) • It have 9 method definitions like – GET – HEAD – POST – PUT – DELETE – TRACE – CONNECT • We can reference more at http://www.w3.org/Protocols/rfc2616/rfc2616- sec9.html
  • 27. Working with HTTP (Verb & return status) • 200 OK • 201 Created • 400 Bad Request • 401 Unauthorized • 404 Not Found • 409 Conflict • 500 Internal Server Error • 501 Not Implemented • Reference more at http://en.wikipedia.org/wiki/List_of_HTTP_status_cod es
  • 28. Format & model binding • Media-Type Formatters // Remove the XML formatter config.Formatters.Remove(config.Formatters.XmlF ormatter); var json = config.Formatters.JsonFormatter; json.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; json.SerializerSettings.Formatting = Formatting.Indented; • Content Negotiation • Model Validation in ASP.NET Web API
  • 29. Dependency Resolver with Autofac var builder = new ContainerBuilder(); // register autofac modules builder.RegisterModule<WebModule>(); builder.RegisterModule<DataSurveyModule>(); builder.RegisterControllers(Assembly.GetExecutingAssembly()); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); builder.RegisterFilterProvider(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
  • 30. Q&A
  • 31. References • http://www.ics.uci.edu/~fielding/pubs/dissert ation/top.htm • http://www.crummy.com/writing/speaking/2 008-QCon/act3.html • http://martinfowler.com/articles/richardsonM aturityModel.html • http://www.asp.net/web-api/