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

Web api 2.0

  • 2.
    Agenda • Premessa • Cos’èe quando si usa WebAPI • Novità della versione 2.0 • Self Hosting (Owin)
  • 3.
  • 4.
  • 5.
  • 6.
    Poi fu ilWeb…
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
    Metodi HTTP • GET •HEAD • POST • PUT • DELETE • TRACE • OPTIONS • CONNECT • PATCH • …
  • 14.
  • 15.
  • 16.
    WCF • Henrik FrystykNielsen – 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.
  • 18.
    Web App Vs.Web Service
  • 19.
    Web Service: WCFVs. 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 allarealizzazione 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 • Attraversouna 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 • Ilbinding 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 • Utilizzatisia 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 WebService con WebAPI (1.0 Vs. 2.0)
  • 28.
  • 29.
    Attribute Routing • Illavoro 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: Casid’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
  • 32.
  • 33.
  • 34.
    DEMO Attribute Routing eIHttpActionResult
  • 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.NETWeb 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 • WebAPI 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 RequestSharing • 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 WebAPI 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 • Ilsupporto 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
  • 42.
  • 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 Microsoftdi Owin: – Server • HTTP Web Server – Component • WebAPI • SignalR • OAuth
  • 45.
  • 46.
    Q&A Tutto il materialedi questa sessione su http://www.communitydays.it/ #CDays13
  • 47.

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!