SlideShare une entreprise Scribd logo
1  sur  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/

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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?
 

Similaire à 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
 

Similaire à 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
 

Plus 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]
 

Plus 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
 

Dernier

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Dernier (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

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/

Notes de l'éditeur

  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.