SlideShare una empresa de Scribd logo
1 de 32
Excellent REST
using ASP.NET WebApi
Maurice de Beijer
2
Who am I?
• Maurice de Beijer
• The Problem Solver
• Microsoft Integration MVP
• DevelopMentor instructor
• Twitter: @mauricedb
• Blog: http://msmvps.com/blogs/theproblemsolver/
• Web: http://www.HTML5Support.nl
• E-mail: mauricedb@develop.com
3
What are we going to cover?
• What is REST?
• What is ASP.NET WebAPI
• Hypermedia
4
What is REST?
Representational State Transfer (REST)
is an architectural style that abstracts
the architectural elements within a
distributed hypermedia system.
Wikipedia
5
What is REST?
• First conceived by Roy Thomas Fielding
– Part of his doctoral thesis from 2000
– One of the original authors of the Hypertext Transfer Protocol
-- HTTP/1.0
• A way of creating “web services”
– Based on the HTTP standard
6
Hypertext Transfer Protocol
The Hypertext Transfer Protocol (HTTP) is an
application-level protocol for distributed,
collaborative, hypermedia information systems.
It is a generic, stateless, protocol which can be
used for many tasks beyond its use for
hypertext.
The Internet Engineering Task Force
7
Richardson Maturity Model
8
ASP.NET WebAPI
ASP.NET Web API is a framework that makes it
easy to build HTTP and REST services using
the .NET framework.
9
WebAPI Controllers
• An ApiController does the work
– Access to the HTTP Request and Response
• Use ModelBinding to ease working with resources
– But also provides HttpRequestMessage for low level access
10
WebAPI Controllers
• Lots of control about sending resources to the client
– HttpResponseMessage
– Content negotiation
• Set any HTTP header you like
– Caching
– Optimistic concurrency
11
WebAPI Controllers
public class DemoController : ApiController
{
// GET api/demo
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
public class DemoController : ApiController
{
// GET api/demo
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
12
WebAPI Routes
• Couple an incoming URL to an ApiController
– Just like with ASP.NET MVC
• Create as many as you like
– The ordering is important!
13
WebAPI Routes
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
14
Content negotiation
• What resource we send != how we send it
– JSON of XML: a book resource is still a book resource
15
MediaTypeFormatter
• The media type specifies the serialization format
– JSON, XML, Word, PDF, VCard etc
• The MediaTypeFormatter (de)serializes
– HTTP <> CLR type
• Content negotiation determines the serialized format
– The client uses the HTTP Accept header
16
MediaTypeFormatter
public class CustomersTextFormatter : BufferedMediaTypeFormatter
{
public CustomersTextFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/text"));
}
public override bool CanWriteType(Type type)
{
return typeof(IEnumerable<Customer>).IsAssignableFrom(type);
}
public override void WriteToStream(Type type, object value,
Stream writeStream, HttpContent content)
{
// ...
}
}
public class CustomersTextFormatter : BufferedMediaTypeFormatter
{
public CustomersTextFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/text"));
}
public override bool CanWriteType(Type type)
{
return typeof(IEnumerable<Customer>).IsAssignableFrom(type);
}
public override void WriteToStream(Type type, object value,
Stream writeStream, HttpContent content)
{
// ...
}
}
17
HTTP Methods
• HTTP supports many HTTP Methods
– With HTML we only use two
• The HTTP Method determines our goal
– Just like the database CRUD actions
18
HTTP Methods
Aktie HTTP Method
Create POST
Read GET
Update (completly replace) PUT
Update (partial replace) PATCH
Delete DELETE
19
WebAPI HTTP Methods
public class DemoController : ApiController {
// GET api/demo
public IEnumerable<string> Get()
// GET api/demo/5
public string Get(int id)
// POST api/demo
public void Post([FromBody]string value)
// PUT api/demo/5
public void Put(int id, [FromBody]string value)
// DELETE api/demo/5
public void Delete(int id)
}
public class DemoController : ApiController {
// GET api/demo
public IEnumerable<string> Get()
// GET api/demo/5
public string Get(int id)
// POST api/demo
public void Post([FromBody]string value)
// PUT api/demo/5
public void Put(int id, [FromBody]string value)
// DELETE api/demo/5
public void Delete(int id)
}
20
Hypermedia - Roy T. Fielding
Hypermedia is defined by the presence of
application control information embedded within, or
as a layer above, the presentation of information.
Distributed hypermedia allows the presentation and
control information to be stored at remote
locations.
Roy T. Fielding
21
Richardson Maturity Model
22
The OData Protocol
• Open Data Protocol (OData)
– A hypermedia web protocol for retrieving and updating data.
– Based on the W3C AtomPub standard
• Can include metadata
• WCF Data Services is an implementation
23
OData metadata
• An OData service can return metadata
– http://www.nerddinner.com/Services/OData.svc/$metadata
• Enables generic clients like PowerPivot for Excel
24
ASP.NET WebAPI and OData
• Standard ApiController’s support basic querying
– $filter
– $orderby
– $skip
– $take
– $expand and $select support coming soon
• Needs to be explicitly enabled
public static void Register(HttpConfiguration config)
{
// Other config
config.EnableQuerySupport();
}
public static void Register(HttpConfiguration config)
{
// Other config
config.EnableQuerySupport();
}
25
OData queries
public class CustomerController : ApiController
{
private NorthwindEntities db =
new NorthwindEntities();
// GET api/Default2
[Queryable(PageSize=10)]
public IQueryable<Customers> GetCustomers()
{
return db.Customers;
}
}
public class CustomerController : ApiController
{
private NorthwindEntities db =
new NorthwindEntities();
// GET api/Default2
[Queryable(PageSize=10)]
public IQueryable<Customers> GetCustomers()
{
return db.Customers;
}
}
26
OData hypermedia controller
• The EntitySetController class can be used for more complete
hypermedia support
• Build in support for Entity Framework Code First
– But we can use any type we want
27
OData metadata support
28
OData hypermedia controller
public class HypermediaBooksController : EntitySetController<Book, int>
{
private readonly IBooksRepository _repo = new BooksRepository();
// GET odata/hypermediaBooks
public override IQueryable<Book> Get()
{
return _repo.GetBooks().AsQueryable();
}
// GET odata/hypermediaBooks(3)
protected override Book GetEntityByKey(int key)
{
return _repo.GetBook(key);
}
}
public class HypermediaBooksController : EntitySetController<Book, int>
{
private readonly IBooksRepository _repo = new BooksRepository();
// GET odata/hypermediaBooks
public override IQueryable<Book> Get()
{
return _repo.GetBooks().AsQueryable();
}
// GET odata/hypermediaBooks(3)
protected override Book GetEntityByKey(int key)
{
return _repo.GetBook(key);
}
}
29
OData hypermedia routing
public static void Register(HttpConfiguration config)
{
// Other config
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Book>("hypermediaBooks");
Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute("ODataRoute", "odata", model);
}
public static void Register(HttpConfiguration config)
{
// Other config
ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Book>("hypermediaBooks");
Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
config.Routes.MapODataRoute("ODataRoute", "odata", model);
}
30
Recommended reading
31
Conclusion
• ASP.NET WebAPI makes REST “easy”
– Even though sometimes ASP.NET MVC is enough
• Think about hypermedia
– Especially when the service is publicly available
32
Questions
?
The presentation and source code will be available
http://msmvps.com/blogs/theproblemsolver/

Más contenido relacionado

La actualidad más candente

Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web APIhabib_786
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical ApproachMadhaiyan Muthu
 
Web API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonWeb API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonAdnan Masood
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using PhpSudheer Satyanarayana
 
Introducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platformIntroducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platformJeffrey T. Fritz
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web APIDamir Dobric
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTPradeep Kumar
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIGert Drapers
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webserviceDong Ngoc
 

La actualidad más candente (20)

Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Web services - A Practical Approach
Web services - A Practical ApproachWeb services - A Practical Approach
Web services - A Practical Approach
 
Web API or WCF - An Architectural Comparison
Web API or WCF - An Architectural ComparisonWeb API or WCF - An Architectural Comparison
Web API or WCF - An Architectural Comparison
 
Web API Basics
Web API BasicsWeb API Basics
Web API Basics
 
Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
Web Services
Web ServicesWeb Services
Web Services
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
 
Introducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platformIntroducing ASP.NET vNext - A tour of the new ASP.NET platform
Introducing ASP.NET vNext - A tour of the new ASP.NET platform
 
Web development with ASP.NET Web API
Web development with ASP.NET Web APIWeb development with ASP.NET Web API
Web development with ASP.NET Web API
 
Web servers
Web serversWeb servers
Web servers
 
What is an API?
What is an API?What is an API?
What is an API?
 
Webservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and RESTWebservices Overview : XML RPC, SOAP and REST
Webservices Overview : XML RPC, SOAP and REST
 
Building RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPIBuilding RESTfull Data Services with WebAPI
Building RESTfull Data Services with WebAPI
 
Soap and restful webservice
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
SOAP-based Web Services
SOAP-based Web ServicesSOAP-based Web Services
SOAP-based Web Services
 
Overview of java web services
Overview of java web servicesOverview of java web services
Overview of java web services
 

Destacado

C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTDr. Awase Khirni Syed
 
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...Maarten Balliauw
 
Very basic of asp.net mvc with c#
Very basic of asp.net mvc with c#Very basic of asp.net mvc with c#
Very basic of asp.net mvc with c#Shreejan Acharya
 
Building great spa’s with angular js, asp.net mvc and webapi
Building great spa’s with angular js, asp.net mvc and webapiBuilding great spa’s with angular js, asp.net mvc and webapi
Building great spa’s with angular js, asp.net mvc and webapiMaurice De Beijer [MVP]
 
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access ControlOAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access ControlMaarten Balliauw
 
REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)Jef Claes
 
Web Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NETWeb Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NETPonraj
 
Microservices Application Simplicity Infrastructure Complexity
Microservices Application Simplicity Infrastructure ComplexityMicroservices Application Simplicity Infrastructure Complexity
Microservices Application Simplicity Infrastructure ComplexityCentric Consulting
 
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-serviceusing ASP.NET Web API and Windows Azure Access ControlOAuth-as-a-serviceusing ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access ControlMaarten Balliauw
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorialAbhi Arya
 
MicroServices, yet another architectural style?
MicroServices, yet another architectural style?MicroServices, yet another architectural style?
MicroServices, yet another architectural style?ACA IT-Solutions
 

Destacado (19)

C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
 
Excellent rest met de web api
Excellent rest met de web apiExcellent rest met de web api
Excellent rest met de web api
 
Treeview listview
Treeview listviewTreeview listview
Treeview listview
 
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control - W...
 
Very basic of asp.net mvc with c#
Very basic of asp.net mvc with c#Very basic of asp.net mvc with c#
Very basic of asp.net mvc with c#
 
Building great spa’s with angular js, asp.net mvc and webapi
Building great spa’s with angular js, asp.net mvc and webapiBuilding great spa’s with angular js, asp.net mvc and webapi
Building great spa’s with angular js, asp.net mvc and webapi
 
REST != WebAPI
REST != WebAPIREST != WebAPI
REST != WebAPI
 
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access ControlOAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
 
Active x
Active xActive x
Active x
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)REST and ASP.NET Web API (Tunisia)
REST and ASP.NET Web API (Tunisia)
 
Wcf development
Wcf developmentWcf development
Wcf development
 
Web Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NETWeb Service Implementation Using ASP.NET
Web Service Implementation Using ASP.NET
 
Microservices Application Simplicity Infrastructure Complexity
Microservices Application Simplicity Infrastructure ComplexityMicroservices Application Simplicity Infrastructure Complexity
Microservices Application Simplicity Infrastructure Complexity
 
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-serviceusing ASP.NET Web API and Windows Azure Access ControlOAuth-as-a-serviceusing ASP.NET Web API and Windows Azure Access Control
OAuth-as-a-service using ASP.NET Web API and Windows Azure Access Control
 
Nunit
NunitNunit
Nunit
 
Web API with ASP.NET MVC by Software development company in india
Web API with ASP.NET  MVC  by Software development company in indiaWeb API with ASP.NET  MVC  by Software development company in india
Web API with ASP.NET MVC by Software development company in india
 
WCF tutorial
WCF tutorialWCF tutorial
WCF tutorial
 
MicroServices, yet another architectural style?
MicroServices, yet another architectural style?MicroServices, yet another architectural style?
MicroServices, yet another architectural style?
 

Similar a Excellent rest using asp.net web api

API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.Andrey Oleynik
 
Hypermedia for Machine APIs
Hypermedia for Machine APIsHypermedia for Machine APIs
Hypermedia for Machine APIsMichael Koster
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesVagif Abilov
 
Connecting to Data from Windows Phone 8
Connecting to Data from Windows Phone 8Connecting to Data from Windows Phone 8
Connecting to Data from Windows Phone 8Woodruff Solutions LLC
 
Connecting to Data from Windows Phone 8 VSLive! Redmond 2013
Connecting to Data from Windows Phone 8 VSLive! Redmond 2013Connecting to Data from Windows Phone 8 VSLive! Redmond 2013
Connecting to Data from Windows Phone 8 VSLive! Redmond 2013Woodruff Solutions LLC
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP TutorialLorna Mitchell
 
Evolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecurityEvolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecuritySanjeev Verma, PhD
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIRasan Samarasinghe
 
Designing RESTful APIs
Designing RESTful APIsDesigning RESTful APIs
Designing RESTful APIsanandology
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid RahimianAPI Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid RahimianVahid Rahimian
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Henry S
 
Arabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, IntroductionArabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, IntroductionJasonRafeMiller
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHPZoran Jeremic
 
Hypermedia System Architecture for a Web of Things
Hypermedia System Architecture for a Web of ThingsHypermedia System Architecture for a Web of Things
Hypermedia System Architecture for a Web of ThingsMichael Koster
 

Similar a Excellent rest using asp.net web api (20)

API Testing. Streamline your testing process.
API Testing. Streamline your testing process.API Testing. Streamline your testing process.
API Testing. Streamline your testing process.
 
Hypermedia for Machine APIs
Hypermedia for Machine APIsHypermedia for Machine APIs
Hypermedia for Machine APIs
 
SOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class LibrariesSOLID Programming with Portable Class Libraries
SOLID Programming with Portable Class Libraries
 
Basics of the Web Platform
Basics of the Web PlatformBasics of the Web Platform
Basics of the Web Platform
 
Kurento cpmx
Kurento cpmxKurento cpmx
Kurento cpmx
 
Connecting to Data from Windows Phone 8
Connecting to Data from Windows Phone 8Connecting to Data from Windows Phone 8
Connecting to Data from Windows Phone 8
 
Connecting to Data from Windows Phone 8 VSLive! Redmond 2013
Connecting to Data from Windows Phone 8 VSLive! Redmond 2013Connecting to Data from Windows Phone 8 VSLive! Redmond 2013
Connecting to Data from Windows Phone 8 VSLive! Redmond 2013
 
Php reports sumit
Php reports sumitPhp reports sumit
Php reports sumit
 
Web Services PHP Tutorial
Web Services PHP TutorialWeb Services PHP Tutorial
Web Services PHP Tutorial
 
Evolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser SecurityEvolution Of The Web Platform & Browser Security
Evolution Of The Web Platform & Browser Security
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
Designing RESTful APIs
Designing RESTful APIsDesigning RESTful APIs
Designing RESTful APIs
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid RahimianAPI Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
API Design, A Quick Guide to REST, SOAP, gRPC, and GraphQL, By Vahid Rahimian
 
Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1Code for Startup MVP (Ruby on Rails) Session 1
Code for Startup MVP (Ruby on Rails) Session 1
 
Arabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, IntroductionArabidopsis Information Portal, Developer Workshop 2014, Introduction
Arabidopsis Information Portal, Developer Workshop 2014, Introduction
 
Web api
Web apiWeb api
Web api
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Hypermedia System Architecture for a Web of Things
Hypermedia System Architecture for a Web of ThingsHypermedia System Architecture for a Web of Things
Hypermedia System Architecture for a Web of Things
 

Más de Maurice De Beijer [MVP]

Practice TypeScript Techniques Building React Server Components App
Practice TypeScript Techniques Building React Server Components AppPractice TypeScript Techniques Building React Server Components App
Practice TypeScript Techniques Building React Server Components AppMaurice De Beijer [MVP]
 
A foolproof Way to Estimate a Software Project
A foolproof Way to Estimate a Software ProjectA foolproof Way to Estimate a Software Project
A foolproof Way to Estimate a Software ProjectMaurice De Beijer [MVP]
 
Surati Tech Talks 2022 / Build reliable Svelte applications using Cypress
Surati Tech Talks 2022 / Build reliable Svelte applications using CypressSurati Tech Talks 2022 / Build reliable Svelte applications using Cypress
Surati Tech Talks 2022 / Build reliable Svelte applications using CypressMaurice De Beijer [MVP]
 
Build reliable Svelte applications using Cypress
Build reliable Svelte applications using CypressBuild reliable Svelte applications using Cypress
Build reliable Svelte applications using CypressMaurice De Beijer [MVP]
 
Building Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & AzureBuilding Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & AzureMaurice De Beijer [MVP]
 
Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18Maurice De Beijer [MVP]
 
Building reliable applications with React, C#, and Azure
Building reliable applications with React, C#, and AzureBuilding reliable applications with React, C#, and Azure
Building reliable applications with React, C#, and AzureMaurice De Beijer [MVP]
 
Building large and scalable mission critical applications with React
Building large and scalable mission critical applications with ReactBuilding large and scalable mission critical applications with React
Building large and scalable mission critical applications with ReactMaurice De Beijer [MVP]
 
Building Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & AzureBuilding Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & AzureMaurice De Beijer [MVP]
 
Building reliable web applications using Cypress
Building reliable web applications using CypressBuilding reliable web applications using Cypress
Building reliable web applications using CypressMaurice De Beijer [MVP]
 
Getting started with React Suspense and concurrent rendering
Getting started with React Suspense and concurrent renderingGetting started with React Suspense and concurrent rendering
Getting started with React Suspense and concurrent renderingMaurice De Beijer [MVP]
 
React suspense, not just for Alfred Hitchcock
React suspense, not just for Alfred HitchcockReact suspense, not just for Alfred Hitchcock
React suspense, not just for Alfred HitchcockMaurice De Beijer [MVP]
 
From zero to hero with the Reactive extensions for JavaScript
From zero to hero with the Reactive extensions for JavaScriptFrom zero to hero with the Reactive extensions for JavaScript
From zero to hero with the Reactive extensions for JavaScriptMaurice De Beijer [MVP]
 
From zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptFrom zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptMaurice De Beijer [MVP]
 
Create flexible React applications using GraphQL apis
Create flexible React applications using GraphQL apisCreate flexible React applications using GraphQL apis
Create flexible React applications using GraphQL apisMaurice De Beijer [MVP]
 

Más de Maurice De Beijer [MVP] (20)

Practice TypeScript Techniques Building React Server Components App
Practice TypeScript Techniques Building React Server Components AppPractice TypeScript Techniques Building React Server Components App
Practice TypeScript Techniques Building React Server Components App
 
A foolproof Way to Estimate a Software Project
A foolproof Way to Estimate a Software ProjectA foolproof Way to Estimate a Software Project
A foolproof Way to Estimate a Software Project
 
Surati Tech Talks 2022 / Build reliable Svelte applications using Cypress
Surati Tech Talks 2022 / Build reliable Svelte applications using CypressSurati Tech Talks 2022 / Build reliable Svelte applications using Cypress
Surati Tech Talks 2022 / Build reliable Svelte applications using Cypress
 
Build reliable Svelte applications using Cypress
Build reliable Svelte applications using CypressBuild reliable Svelte applications using Cypress
Build reliable Svelte applications using Cypress
 
Building Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & AzureBuilding Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & Azure
 
Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18
 
Building reliable applications with React, C#, and Azure
Building reliable applications with React, C#, and AzureBuilding reliable applications with React, C#, and Azure
Building reliable applications with React, C#, and Azure
 
Building large and scalable mission critical applications with React
Building large and scalable mission critical applications with ReactBuilding large and scalable mission critical applications with React
Building large and scalable mission critical applications with React
 
Building Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & AzureBuilding Reliable Applications Using React, .NET & Azure
Building Reliable Applications Using React, .NET & Azure
 
Why I am hooked on the future of React
Why I am hooked on the future of ReactWhy I am hooked on the future of React
Why I am hooked on the future of React
 
Building reliable web applications using Cypress
Building reliable web applications using CypressBuilding reliable web applications using Cypress
Building reliable web applications using Cypress
 
Getting started with React Suspense and concurrent rendering
Getting started with React Suspense and concurrent renderingGetting started with React Suspense and concurrent rendering
Getting started with React Suspense and concurrent rendering
 
React suspense, not just for Alfred Hitchcock
React suspense, not just for Alfred HitchcockReact suspense, not just for Alfred Hitchcock
React suspense, not just for Alfred Hitchcock
 
From zero to hero with the Reactive extensions for JavaScript
From zero to hero with the Reactive extensions for JavaScriptFrom zero to hero with the Reactive extensions for JavaScript
From zero to hero with the Reactive extensions for JavaScript
 
Why I am hooked on the future of React
Why I am hooked on the future of ReactWhy I am hooked on the future of React
Why I am hooked on the future of React
 
The new React
The new React The new React
The new React
 
From zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScriptFrom zero to hero with the reactive extensions for JavaScript
From zero to hero with the reactive extensions for JavaScript
 
Why I am hooked on the future of React
Why I am hooked on the future of ReactWhy I am hooked on the future of React
Why I am hooked on the future of React
 
I am hooked on React
I am hooked on ReactI am hooked on React
I am hooked on React
 
Create flexible React applications using GraphQL apis
Create flexible React applications using GraphQL apisCreate flexible React applications using GraphQL apis
Create flexible React applications using GraphQL apis
 

Último

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Último (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

Excellent rest using asp.net web api

  • 1. Excellent REST using ASP.NET WebApi Maurice de Beijer
  • 2. 2 Who am I? • Maurice de Beijer • The Problem Solver • Microsoft Integration MVP • DevelopMentor instructor • Twitter: @mauricedb • Blog: http://msmvps.com/blogs/theproblemsolver/ • Web: http://www.HTML5Support.nl • E-mail: mauricedb@develop.com
  • 3. 3 What are we going to cover? • What is REST? • What is ASP.NET WebAPI • Hypermedia
  • 4. 4 What is REST? Representational State Transfer (REST) is an architectural style that abstracts the architectural elements within a distributed hypermedia system. Wikipedia
  • 5. 5 What is REST? • First conceived by Roy Thomas Fielding – Part of his doctoral thesis from 2000 – One of the original authors of the Hypertext Transfer Protocol -- HTTP/1.0 • A way of creating “web services” – Based on the HTTP standard
  • 6. 6 Hypertext Transfer Protocol The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. It is a generic, stateless, protocol which can be used for many tasks beyond its use for hypertext. The Internet Engineering Task Force
  • 8. 8 ASP.NET WebAPI ASP.NET Web API is a framework that makes it easy to build HTTP and REST services using the .NET framework.
  • 9. 9 WebAPI Controllers • An ApiController does the work – Access to the HTTP Request and Response • Use ModelBinding to ease working with resources – But also provides HttpRequestMessage for low level access
  • 10. 10 WebAPI Controllers • Lots of control about sending resources to the client – HttpResponseMessage – Content negotiation • Set any HTTP header you like – Caching – Optimistic concurrency
  • 11. 11 WebAPI Controllers public class DemoController : ApiController { // GET api/demo public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } } public class DemoController : ApiController { // GET api/demo public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } }
  • 12. 12 WebAPI Routes • Couple an incoming URL to an ApiController – Just like with ASP.NET MVC • Create as many as you like – The ordering is important!
  • 13. 13 WebAPI Routes public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
  • 14. 14 Content negotiation • What resource we send != how we send it – JSON of XML: a book resource is still a book resource
  • 15. 15 MediaTypeFormatter • The media type specifies the serialization format – JSON, XML, Word, PDF, VCard etc • The MediaTypeFormatter (de)serializes – HTTP <> CLR type • Content negotiation determines the serialized format – The client uses the HTTP Accept header
  • 16. 16 MediaTypeFormatter public class CustomersTextFormatter : BufferedMediaTypeFormatter { public CustomersTextFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/text")); } public override bool CanWriteType(Type type) { return typeof(IEnumerable<Customer>).IsAssignableFrom(type); } public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { // ... } } public class CustomersTextFormatter : BufferedMediaTypeFormatter { public CustomersTextFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/text")); } public override bool CanWriteType(Type type) { return typeof(IEnumerable<Customer>).IsAssignableFrom(type); } public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content) { // ... } }
  • 17. 17 HTTP Methods • HTTP supports many HTTP Methods – With HTML we only use two • The HTTP Method determines our goal – Just like the database CRUD actions
  • 18. 18 HTTP Methods Aktie HTTP Method Create POST Read GET Update (completly replace) PUT Update (partial replace) PATCH Delete DELETE
  • 19. 19 WebAPI HTTP Methods public class DemoController : ApiController { // GET api/demo public IEnumerable<string> Get() // GET api/demo/5 public string Get(int id) // POST api/demo public void Post([FromBody]string value) // PUT api/demo/5 public void Put(int id, [FromBody]string value) // DELETE api/demo/5 public void Delete(int id) } public class DemoController : ApiController { // GET api/demo public IEnumerable<string> Get() // GET api/demo/5 public string Get(int id) // POST api/demo public void Post([FromBody]string value) // PUT api/demo/5 public void Put(int id, [FromBody]string value) // DELETE api/demo/5 public void Delete(int id) }
  • 20. 20 Hypermedia - Roy T. Fielding Hypermedia is defined by the presence of application control information embedded within, or as a layer above, the presentation of information. Distributed hypermedia allows the presentation and control information to be stored at remote locations. Roy T. Fielding
  • 22. 22 The OData Protocol • Open Data Protocol (OData) – A hypermedia web protocol for retrieving and updating data. – Based on the W3C AtomPub standard • Can include metadata • WCF Data Services is an implementation
  • 23. 23 OData metadata • An OData service can return metadata – http://www.nerddinner.com/Services/OData.svc/$metadata • Enables generic clients like PowerPivot for Excel
  • 24. 24 ASP.NET WebAPI and OData • Standard ApiController’s support basic querying – $filter – $orderby – $skip – $take – $expand and $select support coming soon • Needs to be explicitly enabled public static void Register(HttpConfiguration config) { // Other config config.EnableQuerySupport(); } public static void Register(HttpConfiguration config) { // Other config config.EnableQuerySupport(); }
  • 25. 25 OData queries public class CustomerController : ApiController { private NorthwindEntities db = new NorthwindEntities(); // GET api/Default2 [Queryable(PageSize=10)] public IQueryable<Customers> GetCustomers() { return db.Customers; } } public class CustomerController : ApiController { private NorthwindEntities db = new NorthwindEntities(); // GET api/Default2 [Queryable(PageSize=10)] public IQueryable<Customers> GetCustomers() { return db.Customers; } }
  • 26. 26 OData hypermedia controller • The EntitySetController class can be used for more complete hypermedia support • Build in support for Entity Framework Code First – But we can use any type we want
  • 28. 28 OData hypermedia controller public class HypermediaBooksController : EntitySetController<Book, int> { private readonly IBooksRepository _repo = new BooksRepository(); // GET odata/hypermediaBooks public override IQueryable<Book> Get() { return _repo.GetBooks().AsQueryable(); } // GET odata/hypermediaBooks(3) protected override Book GetEntityByKey(int key) { return _repo.GetBook(key); } } public class HypermediaBooksController : EntitySetController<Book, int> { private readonly IBooksRepository _repo = new BooksRepository(); // GET odata/hypermediaBooks public override IQueryable<Book> Get() { return _repo.GetBooks().AsQueryable(); } // GET odata/hypermediaBooks(3) protected override Book GetEntityByKey(int key) { return _repo.GetBook(key); } }
  • 29. 29 OData hypermedia routing public static void Register(HttpConfiguration config) { // Other config ODataModelBuilder modelBuilder = new ODataConventionModelBuilder(); modelBuilder.EntitySet<Book>("hypermediaBooks"); Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel(); config.Routes.MapODataRoute("ODataRoute", "odata", model); } public static void Register(HttpConfiguration config) { // Other config ODataModelBuilder modelBuilder = new ODataConventionModelBuilder(); modelBuilder.EntitySet<Book>("hypermediaBooks"); Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel(); config.Routes.MapODataRoute("ODataRoute", "odata", model); }
  • 31. 31 Conclusion • ASP.NET WebAPI makes REST “easy” – Even though sometimes ASP.NET MVC is enough • Think about hypermedia – Especially when the service is publicly available
  • 32. 32 Questions ? The presentation and source code will be available http://msmvps.com/blogs/theproblemsolver/

Notas del editor

  1. 0: Administration 9/19/2011 Essential HTML5 © 2011 DevelopMentor. All Rights Reserved.
  2. 0: Administration 9/19/2011 Essential HTML5 © 2011 DevelopMentor. All Rights Reserved.