SlideShare a Scribd company logo
Web api 2.0
Agenda
• Premessa
• Cos’è e quando si usa WebAPI
• Novità della versione 2.0
• Self Hosting (Owin)
AGENDA
Premessa storica
Quiz: Li riconoscete?
In principio era Internet
Poi fu il Web…
…infine ASP.NET
Web & Internet
Internet
Web
HTTP
Uniform Resource Locator
Metodi HTTP
• GET
• HEAD
• POST
• PUT
• DELETE
• TRACE
• OPTIONS
• CONNECT
• PATCH
• …
The Microsoft Way
ASP.NET
Sites Services
Web
Forms
Web
Pages
MVC
Single
Page
Web
API
SignalR
ASP.NET
WCF
• Henrik Frystyk Nielsen
– First Graduate Student di Tim Berners-Lee
– In W3C coordina le specifiche di HTTP 1.1
– Nel 1999 in Microsoft lavora a SOAP 1.1
– Principal Architect di WCF e WebAPI
AGENDA
Cos’è e quando si usa WebAPI
Web App Vs. Web Service
Web Service: WCF Vs. WebAPI
• WCF SOAP RPC usa HTTP come mero
protocollo di trasporto, definisce specifici
metodi e mette tutta la comunicazione nel
BODY.
• WebAPI consente lo sviluppo di servizi
RESTful, utilizzando i soli metodi HTTP.
RESTful Web Service
• Un servizio RESTful è un Web Service che
implementa i principi REST e utilizza i
metodi HTTP
REpresentational State Transfer
• Client–server
• Stateless
• Uniform interface (metodi HTTP)
• Cacheable
• Layered system
WebAPI
• Adatto alla realizzazione di servizi REST.
• Usa il routing e il binding per mappare la
richiesta HTTP alla corrispondente azione
del controller.
• A differenza di MVC non ha alcuna View.
• E’ l’azione del controller che, utilizzando il
modello, produce direttamente la risposta.
WebAPI Routing
• Attraverso una serie di convenzioni
predefinite (eventualmente modificabili) a
partire dall’URL della richiesta viene
identificato il controller e la rispettiva
azione da eseguire.
WebAPI Binding
• Il binding della richiesta agli eventuali
parametri dell’azione prevede che:
– I dati semplici siano contenuti nell’URL.
– I dati complessi siano racchiusi in un unico
dato complesso contenuto nel BODY della
richiesta.
WebAPI Formatter
• Utilizzati sia nel binding della richiesta sia
nella produzione della risposta.
• URL Formatter:
– per recuperare i parametri semplici dall’URL.
• Body Formatter:
– JSON (che utilizza JSON.NET).
– XML (DataContractSerializer o XMLSerializer).
JSON Vs. XML
• Il tipo di risposta dipende dall’header della
richiesta.
• WebAPI di default risponde in JSON.
• IE tipicamente usa: Accept: text/html, application/xhtml+xml, */*
• Per ricevere la risposta in XML: Accept: application/xml
DEMO
Creiamo un Web Service con WebAPI (1.0 Vs. 2.0)
AGENDA
Novità di WebAPI 2.0
Attribute Routing
• Il lavoro di Tim McCall (autore di
http://attributerouting.net) è stato
incorporato in ASP.NET WebAPI 2.0.
• Con l’attribute routing è possibile definire
le Web API Route come attributi
direttamente nelle Action e Controller.
Attribute Routing: perché?
• Nella vita reale le entità hanno relazioni
(i.e. Clienti/Fatture/Dettaglio fatture).
• Può essere utile, ad esempio, richiedere le
fatture di un cliente: API/Clients/1/Invoices
• Impostare questo tipo di routing diventa
facile con gli Attribute Routing.
Attribute Routing: Casi d’uso
• API versioning
– Versione 1: /api/v1/products
– Versione 2: /api/v2/products
• Overloaded URI segments
– Un singolo ordine: /orders/1
– Un elenco di ordini pendenti: /orders/pending
• Multiple parameter types
– Parametro di tipo intero: /orders/1
– Parametro di tipo data: /orders/2013/06/16
Attribute Routing: Attivazione
IHttpActionResult
DEMO
Attribute Routing e IHttpActionResult
OData
• $select, $expand, $batch e $value
• Estensibilità dei formatter Odata
• Type-less support
• Riutilizzo di un modello EDM esistente
OData
• $select, $expand, $batch e $value
• Estensibilità dei formatter Odata
• IEdmObject (serializer/deserialiazer OData):
– Type-less support
– Riutilizzo di un modello EDM esistente
Request Batching
• ASP.NET Web API ora supporta diverse
strategie di request batching:
– Usare il $batch endpoint di un servizio OData.
– Unire richieste multiple in una singola "MIME
multipart request".
– Usare un batching format personalizzato.
Unit Testing
• Web API 2 rende molto più semplice fare lo
unit test dei controller.
• Basta istanziare il controller con i propri
"request message" e "configuration", e poi
chiamare l’action method che si vuole testare.
• Si può anche moccare la classe UrlHelper, per
testare le azioni che generano link.
Cross Origin Request Sharing
• Grazie al contributo di Brock Allen, ASP.NET
now fully supports CORS
• Browser security prevents a web page from
making AJAX requests to another domain.
CORS is a W3C standard that allows a server
to relax the same-origin policy. Using CORS, a
server can explicitly allow some cross-origin
requests while rejecting others.
Portable ASP.NET Web API Client
• E’ possibile utilizzare ASP.NET Web API
Client per creare librerie PCL utilizzabili per
applicazioni Windows Store and Windows
Phone 8.
• E’ possibile inoltre creare dei formatter
condivisibili tra client e server.
External Authentication
• Il supporto per OAuth 2.0 è basato sul
nuovo middleware di sicurezza Owin.
• In alternativa, si può utilizzare un server di
autorizzazione come Windows Azure
Active Directory o ADFS in Windows
Server 2012 R2
AGENDA
Self Hosting (Owin)
Owin
• Open standard
• Definisce un'interfaccia per lo sviluppo di
moduli semplici e testabili per lo sviluppo
web su .NET
• Disaccoppiamento tra Web server e
framework component
Katana
• Implementazione Microsoft di Owin:
– Server
• HTTP Web Server
– Component
• WebAPI
• SignalR
• OAuth
DEMO
OData - Self Hosting
Q&A
Tutto il materiale di questa sessione su
http://www.communitydays.it/
#CDays13
Grazie a
Sponsor

More Related Content

PPTX
ASP.NET Web API
PDF
Creare API pubbliche, come evitare gli errori comuni
PPTX
Internet information services
PPTX
Asp.net web api reloaded
PPTX
Fr01 asp.net web api reloaded
PPTX
Esplorando il Cloud con Azure - Un viaggio tra IaaS, PaaS e SaaS e un compila...
PDF
Cloud Google App Engine Paas
PDF
Blazor per uno sviluppatore Web Form
ASP.NET Web API
Creare API pubbliche, come evitare gli errori comuni
Internet information services
Asp.net web api reloaded
Fr01 asp.net web api reloaded
Esplorando il Cloud con Azure - Un viaggio tra IaaS, PaaS e SaaS e un compila...
Cloud Google App Engine Paas
Blazor per uno sviluppatore Web Form

What's hot (19)

PDF
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
PPTX
.Net 4.0 Preview @ UGIdotNet
PPTX
Asp.net web form 4.5 - what's new!!
PPTX
.NET Core, ASP.NET Core e Linux per il Mobile
PPTX
UWP e Mobile App Mobile Services
PDF
REST API fantastiche e dove trovarle
PPTX
Cosa c'è di nuovo in asp.net core 2 0
PPTX
Microservices webinar EMEA Aug. 2017
PPTX
Visual Studio 2013 - A New kind In Town - ASP.NET Web Api 2
PPTX
Asp net (versione 1 e 2)
PPTX
Web sockets
PDF
Blazor ha vinto? Storie di casi reali
PPTX
Asp.Net MVC 5
PDF
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, Piacenza
PDF
ASP.NET Core - Razor Pages
PPTX
Sviluppare Azure Web Apps
PDF
Web frameworks
PPTX
Tutto su ASP.NET Identity
PPTX
Importazione e sincronizzazione di contenuti con Feed Import - SIDCamp 2015
Back to the Future: Migrare da WebForm ad ASP.NET Core gradualmente
.Net 4.0 Preview @ UGIdotNet
Asp.net web form 4.5 - what's new!!
.NET Core, ASP.NET Core e Linux per il Mobile
UWP e Mobile App Mobile Services
REST API fantastiche e dove trovarle
Cosa c'è di nuovo in asp.net core 2 0
Microservices webinar EMEA Aug. 2017
Visual Studio 2013 - A New kind In Town - ASP.NET Web Api 2
Asp net (versione 1 e 2)
Web sockets
Blazor ha vinto? Storie di casi reali
Asp.Net MVC 5
Sviluppo Web con React e Delphi - Seminario Delphi Day 2016, Piacenza
ASP.NET Core - Razor Pages
Sviluppare Azure Web Apps
Web frameworks
Tutto su ASP.NET Identity
Importazione e sincronizzazione di contenuti con Feed Import - SIDCamp 2015
Ad

Similar to Web api 2.0 (20)

PPTX
Web Api – The HTTP Way
PPTX
WebAPI 2.0
PDF
WSO2 MASTER CLASS ITALIA #9 - Come creare API di successo
PPTX
Swagger per tutti
PPTX
Swagger pertutti
PPTX
Creare API pubbliche, come evitare gli errori comuni
PDF
Microsoft Azure for DreamSpark Academic Tour - 22/01/2016
PDF
Happy Monday #1: the Web API guidelines for happy developers
PDF
Rivoluziona il tuo sito con le WP REST API - Andrea Cardinali
PPTX
Applicazioni RESTful con ASP.NET Web Api
PDF
Web services
ODP
Net core base
PPTX
Wcf data services
PDF
Ajax - Presente e futuro delle applicazioni web
PDF
Usare le nuove WCF Web Api per creare servizi RESTful
PPTX
Brokering over WCF @ dotNetMarche
PPTX
Working with http client rest apis and connection availability check
PPTX
Asp.net 4 Community Tour VS2010
PDF
Lezione 11: Accesso ai RESTful Web Services in Java
PPTX
Self hosted Services with .NET OWin
Web Api – The HTTP Way
WebAPI 2.0
WSO2 MASTER CLASS ITALIA #9 - Come creare API di successo
Swagger per tutti
Swagger pertutti
Creare API pubbliche, come evitare gli errori comuni
Microsoft Azure for DreamSpark Academic Tour - 22/01/2016
Happy Monday #1: the Web API guidelines for happy developers
Rivoluziona il tuo sito con le WP REST API - Andrea Cardinali
Applicazioni RESTful con ASP.NET Web Api
Web services
Net core base
Wcf data services
Ajax - Presente e futuro delle applicazioni web
Usare le nuove WCF Web Api per creare servizi RESTful
Brokering over WCF @ dotNetMarche
Working with http client rest apis and connection availability check
Asp.net 4 Community Tour VS2010
Lezione 11: Accesso ai RESTful Web Services in Java
Self hosted Services with .NET OWin
Ad

More from Nicolò Carandini (20)

PDF
Wasm and Blazor CDays keynote
PPTX
The absolute need of Secure Http
PPTX
Christmas greetings cards with blazor
PPTX
Xamarin DevOps
PDF
Code review e pair programming con Visual Studio Live Share
PPTX
Azure dev ops meetup one
PDF
Spa with Blazor
PDF
The Hitchhiker's Guide to the Azure Galaxy
PPTX
Game matching with SignalR
PPTX
Swagger loves WebAPI
PPTX
Xamarin Workbooks
PDF
Web app slots and webapi versioning
PPTX
Intro xamarin forms
PPTX
Windows 10 design
PPTX
Windows 10 IoT
PPTX
Mobile services multi-piattaforma con Xamarin
PPTX
Universal Apps localization and globalization
PPTX
Applicazioni web con ASP.NET Owin e Katana
PPTX
Azure Mobile Services con il .NET Framework
PPTX
Sviluppare app per iOS e Android con Xamarin e Visual Studio
Wasm and Blazor CDays keynote
The absolute need of Secure Http
Christmas greetings cards with blazor
Xamarin DevOps
Code review e pair programming con Visual Studio Live Share
Azure dev ops meetup one
Spa with Blazor
The Hitchhiker's Guide to the Azure Galaxy
Game matching with SignalR
Swagger loves WebAPI
Xamarin Workbooks
Web app slots and webapi versioning
Intro xamarin forms
Windows 10 design
Windows 10 IoT
Mobile services multi-piattaforma con Xamarin
Universal Apps localization and globalization
Applicazioni web con ASP.NET Owin e Katana
Azure Mobile Services con il .NET Framework
Sviluppare app per iOS e Android con Xamarin e Visual Studio

Web api 2.0

  • 2. Agenda • Premessa • Cos’è e quando si usa WebAPI • Novità della versione 2.0 • Self Hosting (Owin)
  • 5. In principio era Internet
  • 6. Poi fu il Web…
  • 10. Web
  • 11. HTTP
  • 13. Metodi HTTP • GET • HEAD • POST • PUT • DELETE • TRACE • OPTIONS • CONNECT • PATCH • …
  • 16. WCF • Henrik Frystyk Nielsen – First Graduate Student di Tim Berners-Lee – In W3C coordina le specifiche di HTTP 1.1 – Nel 1999 in Microsoft lavora a SOAP 1.1 – Principal Architect di WCF e WebAPI
  • 17. AGENDA Cos’è e quando si usa WebAPI
  • 18. Web App Vs. Web Service
  • 19. Web Service: WCF Vs. WebAPI • WCF SOAP RPC usa HTTP come mero protocollo di trasporto, definisce specifici metodi e mette tutta la comunicazione nel BODY. • WebAPI consente lo sviluppo di servizi RESTful, utilizzando i soli metodi HTTP.
  • 20. RESTful Web Service • Un servizio RESTful è un Web Service che implementa i principi REST e utilizza i metodi HTTP
  • 21. REpresentational State Transfer • Client–server • Stateless • Uniform interface (metodi HTTP) • Cacheable • Layered system
  • 22. WebAPI • Adatto alla realizzazione di servizi REST. • Usa il routing e il binding per mappare la richiesta HTTP alla corrispondente azione del controller. • A differenza di MVC non ha alcuna View. • E’ l’azione del controller che, utilizzando il modello, produce direttamente la risposta.
  • 23. WebAPI Routing • Attraverso una serie di convenzioni predefinite (eventualmente modificabili) a partire dall’URL della richiesta viene identificato il controller e la rispettiva azione da eseguire.
  • 24. WebAPI Binding • Il binding della richiesta agli eventuali parametri dell’azione prevede che: – I dati semplici siano contenuti nell’URL. – I dati complessi siano racchiusi in un unico dato complesso contenuto nel BODY della richiesta.
  • 25. WebAPI Formatter • Utilizzati sia nel binding della richiesta sia nella produzione della risposta. • URL Formatter: – per recuperare i parametri semplici dall’URL. • Body Formatter: – JSON (che utilizza JSON.NET). – XML (DataContractSerializer o XMLSerializer).
  • 26. JSON Vs. XML • Il tipo di risposta dipende dall’header della richiesta. • WebAPI di default risponde in JSON. • IE tipicamente usa: Accept: text/html, application/xhtml+xml, */* • Per ricevere la risposta in XML: Accept: application/xml
  • 27. DEMO Creiamo un Web Service con WebAPI (1.0 Vs. 2.0)
  • 29. Attribute Routing • Il lavoro di Tim McCall (autore di http://attributerouting.net) è stato incorporato in ASP.NET WebAPI 2.0. • Con l’attribute routing è possibile definire le Web API Route come attributi direttamente nelle Action e Controller.
  • 30. Attribute Routing: perché? • Nella vita reale le entità hanno relazioni (i.e. Clienti/Fatture/Dettaglio fatture). • Può essere utile, ad esempio, richiedere le fatture di un cliente: API/Clients/1/Invoices • Impostare questo tipo di routing diventa facile con gli Attribute Routing.
  • 31. Attribute Routing: Casi d’uso • API versioning – Versione 1: /api/v1/products – Versione 2: /api/v2/products • Overloaded URI segments – Un singolo ordine: /orders/1 – Un elenco di ordini pendenti: /orders/pending • Multiple parameter types – Parametro di tipo intero: /orders/1 – Parametro di tipo data: /orders/2013/06/16
  • 34. DEMO Attribute Routing e IHttpActionResult
  • 35. OData • $select, $expand, $batch e $value • Estensibilità dei formatter Odata • Type-less support • Riutilizzo di un modello EDM esistente
  • 36. OData • $select, $expand, $batch e $value • Estensibilità dei formatter Odata • IEdmObject (serializer/deserialiazer OData): – Type-less support – Riutilizzo di un modello EDM esistente
  • 37. Request Batching • ASP.NET Web API ora supporta diverse strategie di request batching: – Usare il $batch endpoint di un servizio OData. – Unire richieste multiple in una singola "MIME multipart request". – Usare un batching format personalizzato.
  • 38. Unit Testing • Web API 2 rende molto più semplice fare lo unit test dei controller. • Basta istanziare il controller con i propri "request message" e "configuration", e poi chiamare l’action method che si vuole testare. • Si può anche moccare la classe UrlHelper, per testare le azioni che generano link.
  • 39. Cross Origin Request Sharing • Grazie al contributo di Brock Allen, ASP.NET now fully supports CORS • Browser security prevents a web page from making AJAX requests to another domain. CORS is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.
  • 40. Portable ASP.NET Web API Client • E’ possibile utilizzare ASP.NET Web API Client per creare librerie PCL utilizzabili per applicazioni Windows Store and Windows Phone 8. • E’ possibile inoltre creare dei formatter condivisibili tra client e server.
  • 41. External Authentication • Il supporto per OAuth 2.0 è basato sul nuovo middleware di sicurezza Owin. • In alternativa, si può utilizzare un server di autorizzazione come Windows Azure Active Directory o ADFS in Windows Server 2012 R2
  • 43. Owin • Open standard • Definisce un'interfaccia per lo sviluppo di moduli semplici e testabili per lo sviluppo web su .NET • Disaccoppiamento tra Web server e framework component
  • 44. Katana • Implementazione Microsoft di Owin: – Server • HTTP Web Server – Component • WebAPI • SignalR • OAuth
  • 45. DEMO OData - Self Hosting
  • 46. Q&A Tutto il materiale di questa sessione su http://www.communitydays.it/ #CDays13

Editor's Notes

  • #2: Inserite l’eventuale vostro logo in basso a destra
  • #6: Dal 1973 al 1978 Cerf ha condotto con Robert Kahn la ricerca che sviluppò e collaudò i protocolli di comunicazione TCP/IP e la stessa rete Internet come la conosciamo noi oggi. Alla fine del 1982 i nuovi protocolli, collaudati, erano in grado di sostituire i vecchi protocolli nel progetto ARPANET. La data fissata per il passaggio fu il 1º gennaio 1983.
  • #7: Inventore dell’ipertesto, di HTTP e HTML
  • #9: Internet (sviluppato dal 1973 al 1978, sostituisce DARPANET nel 1981) WWW (nasce al CERN nel 1990 con una proposta per un finanziamento della ricerca, NON approvato!)
  • #11: I due elementi principali, costituenti del Web sono HTTP e HTML
  • #14: GET: Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. HEAD: Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content. POST: Requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI. The data POSTed might be, as examples, an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or comment thread; a block of data that is the result of submitting a web form to a data-handling process; or an item to add to a database. PUT: Requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI. DELETE: Deletes the specified resource. TRACE: Echoes back the received request so that a client can see what (if any) changes or additions have been made by intermediate servers. OPTIONS: Returns the HTTP methods that the server supports for the specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource. CONNECT: Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy. PATCH: Is used to apply partial modifications to a resource.[
  • #15: Scott Guthrie è l’uomo chiave di ASP.NET ASP.NET 1.0: Gennaio 2002 ASP.NET 1.1 con Scott Guthrie: Aprile 2003
  • #19: Il trasporto è internet, la comunicazione è HTTP, il tutto qui è dunque il Web. La divisione lato client è più confusa di quello che viene qui schematizzato, lato server è semplice: Da una parte viene prodotta la pagina Web, da l’altra dati in formato JSON / XML
  • #21: GET: Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. HEAD: Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content. POST: Requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI. The data POSTed might be, as examples, an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or comment thread; a block of data that is the result of submitting a web form to a data-handling process; or an item to add to a database. PUT: Requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI. DELETE: Deletes the specified resource. TRACE: Echoes back the received request so that a client can see what (if any) changes or additions have been made by intermediate servers. OPTIONS: Returns the HTTP methods that the server supports for the specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource. CONNECT: Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy. PATCH: Is used to apply partial modifications to a resource.[
  • #22: GET: Requests a representation of the specified resource. Requests using GET should only retrieve data and should have no other effect. HEAD: Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content. POST: Requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI. The data POSTed might be, as examples, an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or comment thread; a block of data that is the result of submitting a web form to a data-handling process; or an item to add to a database. PUT: Requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI. DELETE: Deletes the specified resource. TRACE: Echoes back the received request so that a client can see what (if any) changes or additions have been made by intermediate servers. OPTIONS: Returns the HTTP methods that the server supports for the specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource. CONNECT: Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy. PATCH: Is used to apply partial modifications to a resource.[
  • #47: Ultima slide, obbligatoria
  • #48: Slide da mostrare prima di iniziare la sessione – non rimuovere!