SlideShare a Scribd company logo
Sviluppare servizi self hosted
con il .NET Framework
Nicolò Carandini
Visual C# MVP
Checklist
⃣ Web & Tools evolution
⃣ OWIN: Open Web Interface for .NET
⃣ Katana : Microsoft Owin
⃣ Moduli e Pipeline
⃣ Self-Host in un’app Console
⃣ Self-Host su Azure Work role
⃣ Costruire un modulo custom
Web & Tools evolution
2002 2013
569 milioni 2,4 miliardi
46 minuti al giorno
3 milioni
4 ore al giorno
555 milioni
Static File Serving
Dynamic Page
Generation
Web API
Real-Time
Push Notifications
...
Modern Web App
Tool: Evoluzione del modello di rilascio
• ASP.NET incluso nel .NET Framework
– Almeno un anno tra un rilascio e l’altro
• ASP.NET MVC e WebAPI stand-alone
– Rilasci intra-annuali
• "One ASP.NET" modulare
– Rilasci frequenti e indipendenti dei singoli moduli
tramite NuGet
Hosting
IIS Web Server
è sempre la scelta giusta?
Hosting: IIS web server
Reliability
Scalable Web
Infrastructure
Dynamic Caching and
Compression
Rich Diagnostic Tools
Choice
ASP.NET and PHP
Support
Modular and
Extensible Web Server
Integrated Media
Platform
Security
Enhanced Server
Protection
Secure Content
Publishing
Access Protection
Control
Centralized
Web Farm
Management
Delegated Remote
Management
Powerful
Admin Tools
Web Hosting: IIS pro/versus
• Pro
– È un sistema integrato, potente ed affidabile
– È "da sempre" modulare (HttpModules, HttpHandlers)
• Contro
– È monolitico (prendi tutto o niente)
– Unifica le funzioni di Host e di Server
– I moduli non sono facilmente testabili
– I moduli devono essere riscritti se li si vuol far "girare"
in un altro Host
Verso una nuova architettura
Host
Server
Application
Middleware
Framework
Con un nuovo standard
OWIN: Open Web Interface for .NET
• Cos’è:
Una specifica che descrive un’interfaccia standard
tra .NET web servers e .NET applications
• A cosa serve:
Disaccoppiando le diverse parti che compongono il
server e l’applicazione, consente di scrivere moduli
facilmente testabili che possono girare senza
modifiche su Host di diverso tipo.
OWIN: environment dictionary
Key Name Value Description
"owin.RequestBody" A Stream with the request body, if any. Stream.Null MAY be used
as a placeholder if there is no request body.
"owin.RequestHeaders" An IDictionary<string, string[]> of request headers.
"owin.RequestMethod" A string containing the HTTP request method of the request (e.g.,
"GET", "POST").
"owin.RequestPath" A string containing the request path. The path MUST be relative to
the "root" of the application delegate.
"owin.RequestPathBase" A string containing the portion of the request path corresponding
to the "root" of the application delegate.
"owin.RequestProtocol" A string containing the protocol name and version (e.g. "HTTP/1.0"
or "HTTP/1.1").
"owin.RequestQueryString" A string containing the query string component of the HTTP
request URI, without the leading “?” (e.g., "foo=bar&baz=quux").
The value may be an empty string.
"owin.RequestScheme" A string containing the URI scheme used for the request (e.g.,
"http", "https").
• IDictionary<string, object>
OWIN: application delegate
• Func<IDictionary<string, object>, Task>
Host
Server
Environment
Dictionary Application
OWIN: Host loader
All’avvio, l’Host si incarica di mettere insieme
tutte le parti:
• Crea l‘environment dictionary
• Istanzia il Server
• Chiama il codice di setup dell’applicazione
ottenendo come risultato l’application delegate
• Consegna al Server l’application delegate che è
l’application entry point
OWIN: request execution
Per ogni richiesta HTTP:
• Il server chiama l’applicazione tramite
l’application delegate fornendo come
argomento il dizionario contenente i
dati della richiesta e della risposta.
• L’applicazione popola la risposta o
restituisce un errore.
Hosting: IIS Vs. OWIN
Internet Information Server
Classic / Integrated
CGI
Compression
Request Tracing
Authentication
OWIN Based Host
All avvio viene
costruita la
pipeline con i soli
componenti
necessari
Microsoft Owin (aka Katana)
• Microsoft OWIN è formato dall’insieme dei
componenti OWIN che pur essendo open
source, sono costruiti e rilasciati da Microsoft.
• L’insieme comprende sia componenti
infrastrutturali, come Host e Server, sia
componenti funzionali, come i moduli di
autenticazione e di binding a framework quali
SignalR e ASP.NET Web API.
OWIN: Host
• Ci sono diverse implementazioni:
Custom Host: Microsoft.Owin.SelfHost
IIS/ASP.NET: Microsoft.Owin.Host.SystemWeb
OWIN: custom host
OWIN Host
WebServer (HttpListener)
Static filesWe
Authentication
WebAPI
SignalR
OwinPipeline
Middleware
Component
Server
Component
Framework
Component
OWIN: IIS host
OWIN Middleware Component
Tutti i packages Microsoft.Owin.Security.* che fanno
parte del nuovo Identity System di Visual Studio 2013
(i.e. Cookies, Microsoft Account, Google, Facebook,
Twitter, Bearer Token, OAuth, Authorization server, JWT,
Windows Azure Active directory, and Active directory
federation services) sono realizzati come “OWIN
Middleware Component” e possono essere usati in
entrambi gli scenari self-hosted e IIS-hosted.
Demo
Servizio WebAPI:
• Self-Host in una Console app
• Self-Host su Azure Work role
Moduli e pipeline: IAppBuilder
public interface IAppBuilder
{
IDictionary<string, object> Properties { get; }
object Build(Type returnType);
IAppBuilder New();
IAppBuilder Use(object middleware, params object[] args);
}
public static class AppBuilderUseExtensions
{
public static IAppBuilder Use<T>(this IAppBuilder app, params object[] args)
public static void Run(this IAppBuilder app, Func<IOwinContext, Task> handler)
public static IAppBuilder Use(this IAppBuilder app,
Func<IOwinContext, Func<Task>, Task> handler)
}
Moduli e pipeline: AppBuilder
namespace Microsoft.Owin.Builder
{
using AppFunc = Func<IDictionary<string, object>, Task>;
/// <summary>
/// A standard implementation of IAppBuilder
/// </summary>
public class AppBuilder : IAppBuilder
{
private static readonly AppFunc NotFound = new NotFound().Invoke;
private readonly IList<Tuple<Type, Delegate, object[]>> _middleware;
private readonly IDictionary<Tuple<Type, Type>, Delegate> _conversions;
private readonly IDictionary<string, object> _properties;
Creazione della pipeline
Il Loader:
• Crea una istanza di AppBuilder
• Identifica la classe di startup
• Chiama il metodo Configuration(IAppBuilder app)
• Crea una lista ordinata dei componenti con gli
associati parametri di creazione
• Istanzia i componenti passando a ciascuno il
componente successivo e i parametri di creazione.
Funzionamento della pipeline
La chiamata al primo componente produce
l’esecuzione di tutti i componenti della pipeline:
Middleware
Middleware
Middleware
Empty Middleware
Microsoft Owin: application
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Run(context =>
{
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync("Hello, world.");
});
}
}
Costruire un modulo custom
public class LoggerMiddleware : OwinMiddleware
{
private readonly ILog _logger;
public LoggerMiddleware(OwinMiddleware next, ILog logger)
: base(next)
{
_logger = logger;
}
public override async Task Invoke(IOwinContext context)
{
_logger.LogInfo("Middleware begin");
await this.Next.Invoke(context);
_logger.LogInfo("Middleware end");
}
}
Utilizzare un modulo custom
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.Use<LoggerMiddleware>(new EasyLogger());
...
}
}
Demo
Aggiunta del componente LoggerMiddleware
alla pipeline del nostro servizio web.
Question Time
Con il contributo di
Thank You

More Related Content

Similar to Self hosted Services with .NET OWin

Le novita di visual studio 2012
Le novita di visual studio 2012Le novita di visual studio 2012
Le novita di visual studio 2012Crismer La Pignola
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
Pietro Libro
 
Sviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRailSviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRailStefano Ottaviani
 
What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012
Andrea Dottor
 
Sviluppare Azure Web Apps
Sviluppare Azure Web AppsSviluppare Azure Web Apps
Sviluppare Azure Web Apps
Andrea Dottor
 
Applicazioni RESTful con ASP.NET Web Api
Applicazioni RESTful con ASP.NET Web ApiApplicazioni RESTful con ASP.NET Web Api
Applicazioni RESTful con ASP.NET Web Api
Pietro Libro
 
Swagger per tutti
Swagger per tuttiSwagger per tutti
Swagger per tutti
Nicolò Carandini
 
Esposizione RIA
Esposizione RIAEsposizione RIA
Esposizione RIA
diodorato
 
Asp.net web form 4.5 - what's new!!
Asp.net web form 4.5 - what's new!!Asp.net web form 4.5 - what's new!!
Asp.net web form 4.5 - what's new!!
Massimo Bonanni
 
Web api 2.0
Web api 2.0Web api 2.0
Web api 2.0
Nicolò Carandini
 
Asp net (versione 1 e 2)
Asp net (versione 1 e 2)Asp net (versione 1 e 2)
Asp net (versione 1 e 2)
Felice Pescatore
 
ASP.NET MVC: Andare oltre il 100% (Web@work)
ASP.NET MVC: Andare oltre il 100% (Web@work)ASP.NET MVC: Andare oltre il 100% (Web@work)
ASP.NET MVC: Andare oltre il 100% (Web@work)
Giorgio Di Nardo
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client
Sabino Labarile
 
ASP.NET 4.6 e ASP.NET 5...l'evoluzione del web
ASP.NET 4.6 e ASP.NET 5...l'evoluzione del webASP.NET 4.6 e ASP.NET 5...l'evoluzione del web
ASP.NET 4.6 e ASP.NET 5...l'evoluzione del web
Andrea Dottor
 
SUE AGILE Framework (Italiano)
SUE AGILE Framework (Italiano)SUE AGILE Framework (Italiano)
SUE AGILE Framework (Italiano)
Sabino Labarile
 
Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010
Fabrizio Bernabei
 
Meetup ASP.NET Core Angular
Meetup ASP.NET Core AngularMeetup ASP.NET Core Angular
Meetup ASP.NET Core Angular
dotnetcode
 
Alessandro Forte - ASP.Net 4.0
Alessandro Forte - ASP.Net 4.0Alessandro Forte - ASP.Net 4.0
Alessandro Forte - ASP.Net 4.0
Alessandro Forte
 
Cert03 70-486 developing asp.net mvc 4 web applications
Cert03   70-486 developing asp.net mvc 4 web applicationsCert03   70-486 developing asp.net mvc 4 web applications
Cert03 70-486 developing asp.net mvc 4 web applicationsDotNetCampus
 
SVILUPPO DI SERVIZI REST PER ANDROID
SVILUPPO DI SERVIZI REST PER ANDROIDSVILUPPO DI SERVIZI REST PER ANDROID
SVILUPPO DI SERVIZI REST PER ANDROID
Luca Masini
 

Similar to Self hosted Services with .NET OWin (20)

Le novita di visual studio 2012
Le novita di visual studio 2012Le novita di visual studio 2012
Le novita di visual studio 2012
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Sviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRailSviluppo Web Agile Con MonoRail
Sviluppo Web Agile Con MonoRail
 
What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012What's New in ASP.NET 4.5 and Visual Studio 2012
What's New in ASP.NET 4.5 and Visual Studio 2012
 
Sviluppare Azure Web Apps
Sviluppare Azure Web AppsSviluppare Azure Web Apps
Sviluppare Azure Web Apps
 
Applicazioni RESTful con ASP.NET Web Api
Applicazioni RESTful con ASP.NET Web ApiApplicazioni RESTful con ASP.NET Web Api
Applicazioni RESTful con ASP.NET Web Api
 
Swagger per tutti
Swagger per tuttiSwagger per tutti
Swagger per tutti
 
Esposizione RIA
Esposizione RIAEsposizione RIA
Esposizione RIA
 
Asp.net web form 4.5 - what's new!!
Asp.net web form 4.5 - what's new!!Asp.net web form 4.5 - what's new!!
Asp.net web form 4.5 - what's new!!
 
Web api 2.0
Web api 2.0Web api 2.0
Web api 2.0
 
Asp net (versione 1 e 2)
Asp net (versione 1 e 2)Asp net (versione 1 e 2)
Asp net (versione 1 e 2)
 
ASP.NET MVC: Andare oltre il 100% (Web@work)
ASP.NET MVC: Andare oltre il 100% (Web@work)ASP.NET MVC: Andare oltre il 100% (Web@work)
ASP.NET MVC: Andare oltre il 100% (Web@work)
 
E suap - tecnologie client
E suap - tecnologie client E suap - tecnologie client
E suap - tecnologie client
 
ASP.NET 4.6 e ASP.NET 5...l'evoluzione del web
ASP.NET 4.6 e ASP.NET 5...l'evoluzione del webASP.NET 4.6 e ASP.NET 5...l'evoluzione del web
ASP.NET 4.6 e ASP.NET 5...l'evoluzione del web
 
SUE AGILE Framework (Italiano)
SUE AGILE Framework (Italiano)SUE AGILE Framework (Italiano)
SUE AGILE Framework (Italiano)
 
Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010Asp.net 4 Community Tour VS2010
Asp.net 4 Community Tour VS2010
 
Meetup ASP.NET Core Angular
Meetup ASP.NET Core AngularMeetup ASP.NET Core Angular
Meetup ASP.NET Core Angular
 
Alessandro Forte - ASP.Net 4.0
Alessandro Forte - ASP.Net 4.0Alessandro Forte - ASP.Net 4.0
Alessandro Forte - ASP.Net 4.0
 
Cert03 70-486 developing asp.net mvc 4 web applications
Cert03   70-486 developing asp.net mvc 4 web applicationsCert03   70-486 developing asp.net mvc 4 web applications
Cert03 70-486 developing asp.net mvc 4 web applications
 
SVILUPPO DI SERVIZI REST PER ANDROID
SVILUPPO DI SERVIZI REST PER ANDROIDSVILUPPO DI SERVIZI REST PER ANDROID
SVILUPPO DI SERVIZI REST PER ANDROID
 

More from Nicolò Carandini

Wasm and Blazor CDays keynote
Wasm and Blazor CDays keynoteWasm and Blazor CDays keynote
Wasm and Blazor CDays keynote
Nicolò Carandini
 
The absolute need of Secure Http
The absolute need of Secure HttpThe absolute need of Secure Http
The absolute need of Secure Http
Nicolò Carandini
 
Christmas greetings cards with blazor
Christmas greetings cards with blazorChristmas greetings cards with blazor
Christmas greetings cards with blazor
Nicolò Carandini
 
Xamarin DevOps
Xamarin DevOpsXamarin DevOps
Xamarin DevOps
Nicolò Carandini
 
Code review e pair programming con Visual Studio Live Share
Code review e pair programming con Visual Studio Live ShareCode review e pair programming con Visual Studio Live Share
Code review e pair programming con Visual Studio Live Share
Nicolò Carandini
 
Azure dev ops meetup one
Azure dev ops meetup oneAzure dev ops meetup one
Azure dev ops meetup one
Nicolò Carandini
 
Spa with Blazor
Spa with BlazorSpa with Blazor
Spa with Blazor
Nicolò Carandini
 
The Hitchhiker's Guide to the Azure Galaxy
The Hitchhiker's Guide to the Azure GalaxyThe Hitchhiker's Guide to the Azure Galaxy
The Hitchhiker's Guide to the Azure Galaxy
Nicolò Carandini
 
Game matching with SignalR
Game matching with SignalRGame matching with SignalR
Game matching with SignalR
Nicolò Carandini
 
Swagger loves WebAPI
Swagger loves WebAPISwagger loves WebAPI
Swagger loves WebAPI
Nicolò Carandini
 
Xamarin Workbooks
Xamarin WorkbooksXamarin Workbooks
Xamarin Workbooks
Nicolò Carandini
 
Web app slots and webapi versioning
Web app slots and webapi versioningWeb app slots and webapi versioning
Web app slots and webapi versioning
Nicolò Carandini
 
Intro xamarin forms
Intro xamarin formsIntro xamarin forms
Intro xamarin forms
Nicolò Carandini
 
Swagger pertutti
Swagger pertuttiSwagger pertutti
Swagger pertutti
Nicolò Carandini
 
Windows 10 design
Windows 10 designWindows 10 design
Windows 10 design
Nicolò Carandini
 
Windows 10 IoT
Windows 10 IoTWindows 10 IoT
Windows 10 IoT
Nicolò Carandini
 
Mobile services multi-piattaforma con Xamarin
Mobile services multi-piattaforma con XamarinMobile services multi-piattaforma con Xamarin
Mobile services multi-piattaforma con Xamarin
Nicolò Carandini
 
Universal Apps localization and globalization
Universal Apps localization and globalizationUniversal Apps localization and globalization
Universal Apps localization and globalization
Nicolò Carandini
 
Azure Mobile Services con il .NET Framework
Azure Mobile Services con il .NET FrameworkAzure Mobile Services con il .NET Framework
Azure Mobile Services con il .NET Framework
Nicolò Carandini
 
Sviluppare app per iOS e Android con Xamarin e Visual Studio
Sviluppare app per iOS e Android con Xamarin e Visual StudioSviluppare app per iOS e Android con Xamarin e Visual Studio
Sviluppare app per iOS e Android con Xamarin e Visual Studio
Nicolò Carandini
 

More from Nicolò Carandini (20)

Wasm and Blazor CDays keynote
Wasm and Blazor CDays keynoteWasm and Blazor CDays keynote
Wasm and Blazor CDays keynote
 
The absolute need of Secure Http
The absolute need of Secure HttpThe absolute need of Secure Http
The absolute need of Secure Http
 
Christmas greetings cards with blazor
Christmas greetings cards with blazorChristmas greetings cards with blazor
Christmas greetings cards with blazor
 
Xamarin DevOps
Xamarin DevOpsXamarin DevOps
Xamarin DevOps
 
Code review e pair programming con Visual Studio Live Share
Code review e pair programming con Visual Studio Live ShareCode review e pair programming con Visual Studio Live Share
Code review e pair programming con Visual Studio Live Share
 
Azure dev ops meetup one
Azure dev ops meetup oneAzure dev ops meetup one
Azure dev ops meetup one
 
Spa with Blazor
Spa with BlazorSpa with Blazor
Spa with Blazor
 
The Hitchhiker's Guide to the Azure Galaxy
The Hitchhiker's Guide to the Azure GalaxyThe Hitchhiker's Guide to the Azure Galaxy
The Hitchhiker's Guide to the Azure Galaxy
 
Game matching with SignalR
Game matching with SignalRGame matching with SignalR
Game matching with SignalR
 
Swagger loves WebAPI
Swagger loves WebAPISwagger loves WebAPI
Swagger loves WebAPI
 
Xamarin Workbooks
Xamarin WorkbooksXamarin Workbooks
Xamarin Workbooks
 
Web app slots and webapi versioning
Web app slots and webapi versioningWeb app slots and webapi versioning
Web app slots and webapi versioning
 
Intro xamarin forms
Intro xamarin formsIntro xamarin forms
Intro xamarin forms
 
Swagger pertutti
Swagger pertuttiSwagger pertutti
Swagger pertutti
 
Windows 10 design
Windows 10 designWindows 10 design
Windows 10 design
 
Windows 10 IoT
Windows 10 IoTWindows 10 IoT
Windows 10 IoT
 
Mobile services multi-piattaforma con Xamarin
Mobile services multi-piattaforma con XamarinMobile services multi-piattaforma con Xamarin
Mobile services multi-piattaforma con Xamarin
 
Universal Apps localization and globalization
Universal Apps localization and globalizationUniversal Apps localization and globalization
Universal Apps localization and globalization
 
Azure Mobile Services con il .NET Framework
Azure Mobile Services con il .NET FrameworkAzure Mobile Services con il .NET Framework
Azure Mobile Services con il .NET Framework
 
Sviluppare app per iOS e Android con Xamarin e Visual Studio
Sviluppare app per iOS e Android con Xamarin e Visual StudioSviluppare app per iOS e Android con Xamarin e Visual Studio
Sviluppare app per iOS e Android con Xamarin e Visual Studio
 

Self hosted Services with .NET OWin

  • 1. Sviluppare servizi self hosted con il .NET Framework Nicolò Carandini Visual C# MVP
  • 2. Checklist ⃣ Web & Tools evolution ⃣ OWIN: Open Web Interface for .NET ⃣ Katana : Microsoft Owin ⃣ Moduli e Pipeline ⃣ Self-Host in un’app Console ⃣ Self-Host su Azure Work role ⃣ Costruire un modulo custom
  • 3. Web & Tools evolution 2002 2013 569 milioni 2,4 miliardi 46 minuti al giorno 3 milioni 4 ore al giorno 555 milioni Static File Serving Dynamic Page Generation Web API Real-Time Push Notifications ... Modern Web App
  • 4. Tool: Evoluzione del modello di rilascio • ASP.NET incluso nel .NET Framework – Almeno un anno tra un rilascio e l’altro • ASP.NET MVC e WebAPI stand-alone – Rilasci intra-annuali • "One ASP.NET" modulare – Rilasci frequenti e indipendenti dei singoli moduli tramite NuGet
  • 5. Hosting IIS Web Server è sempre la scelta giusta?
  • 6. Hosting: IIS web server Reliability Scalable Web Infrastructure Dynamic Caching and Compression Rich Diagnostic Tools Choice ASP.NET and PHP Support Modular and Extensible Web Server Integrated Media Platform Security Enhanced Server Protection Secure Content Publishing Access Protection Control Centralized Web Farm Management Delegated Remote Management Powerful Admin Tools
  • 7. Web Hosting: IIS pro/versus • Pro – È un sistema integrato, potente ed affidabile – È "da sempre" modulare (HttpModules, HttpHandlers) • Contro – È monolitico (prendi tutto o niente) – Unifica le funzioni di Host e di Server – I moduli non sono facilmente testabili – I moduli devono essere riscritti se li si vuol far "girare" in un altro Host
  • 8. Verso una nuova architettura Host Server Application Middleware Framework
  • 9. Con un nuovo standard OWIN: Open Web Interface for .NET • Cos’è: Una specifica che descrive un’interfaccia standard tra .NET web servers e .NET applications • A cosa serve: Disaccoppiando le diverse parti che compongono il server e l’applicazione, consente di scrivere moduli facilmente testabili che possono girare senza modifiche su Host di diverso tipo.
  • 10. OWIN: environment dictionary Key Name Value Description "owin.RequestBody" A Stream with the request body, if any. Stream.Null MAY be used as a placeholder if there is no request body. "owin.RequestHeaders" An IDictionary<string, string[]> of request headers. "owin.RequestMethod" A string containing the HTTP request method of the request (e.g., "GET", "POST"). "owin.RequestPath" A string containing the request path. The path MUST be relative to the "root" of the application delegate. "owin.RequestPathBase" A string containing the portion of the request path corresponding to the "root" of the application delegate. "owin.RequestProtocol" A string containing the protocol name and version (e.g. "HTTP/1.0" or "HTTP/1.1"). "owin.RequestQueryString" A string containing the query string component of the HTTP request URI, without the leading “?” (e.g., "foo=bar&baz=quux"). The value may be an empty string. "owin.RequestScheme" A string containing the URI scheme used for the request (e.g., "http", "https"). • IDictionary<string, object>
  • 11. OWIN: application delegate • Func<IDictionary<string, object>, Task> Host Server Environment Dictionary Application
  • 12. OWIN: Host loader All’avvio, l’Host si incarica di mettere insieme tutte le parti: • Crea l‘environment dictionary • Istanzia il Server • Chiama il codice di setup dell’applicazione ottenendo come risultato l’application delegate • Consegna al Server l’application delegate che è l’application entry point
  • 13. OWIN: request execution Per ogni richiesta HTTP: • Il server chiama l’applicazione tramite l’application delegate fornendo come argomento il dizionario contenente i dati della richiesta e della risposta. • L’applicazione popola la risposta o restituisce un errore.
  • 14. Hosting: IIS Vs. OWIN Internet Information Server Classic / Integrated CGI Compression Request Tracing Authentication OWIN Based Host All avvio viene costruita la pipeline con i soli componenti necessari
  • 15. Microsoft Owin (aka Katana) • Microsoft OWIN è formato dall’insieme dei componenti OWIN che pur essendo open source, sono costruiti e rilasciati da Microsoft. • L’insieme comprende sia componenti infrastrutturali, come Host e Server, sia componenti funzionali, come i moduli di autenticazione e di binding a framework quali SignalR e ASP.NET Web API.
  • 16. OWIN: Host • Ci sono diverse implementazioni: Custom Host: Microsoft.Owin.SelfHost IIS/ASP.NET: Microsoft.Owin.Host.SystemWeb
  • 17. OWIN: custom host OWIN Host WebServer (HttpListener) Static filesWe Authentication WebAPI SignalR OwinPipeline Middleware Component Server Component Framework Component
  • 19. OWIN Middleware Component Tutti i packages Microsoft.Owin.Security.* che fanno parte del nuovo Identity System di Visual Studio 2013 (i.e. Cookies, Microsoft Account, Google, Facebook, Twitter, Bearer Token, OAuth, Authorization server, JWT, Windows Azure Active directory, and Active directory federation services) sono realizzati come “OWIN Middleware Component” e possono essere usati in entrambi gli scenari self-hosted e IIS-hosted.
  • 20. Demo Servizio WebAPI: • Self-Host in una Console app • Self-Host su Azure Work role
  • 21. Moduli e pipeline: IAppBuilder public interface IAppBuilder { IDictionary<string, object> Properties { get; } object Build(Type returnType); IAppBuilder New(); IAppBuilder Use(object middleware, params object[] args); } public static class AppBuilderUseExtensions { public static IAppBuilder Use<T>(this IAppBuilder app, params object[] args) public static void Run(this IAppBuilder app, Func<IOwinContext, Task> handler) public static IAppBuilder Use(this IAppBuilder app, Func<IOwinContext, Func<Task>, Task> handler) }
  • 22. Moduli e pipeline: AppBuilder namespace Microsoft.Owin.Builder { using AppFunc = Func<IDictionary<string, object>, Task>; /// <summary> /// A standard implementation of IAppBuilder /// </summary> public class AppBuilder : IAppBuilder { private static readonly AppFunc NotFound = new NotFound().Invoke; private readonly IList<Tuple<Type, Delegate, object[]>> _middleware; private readonly IDictionary<Tuple<Type, Type>, Delegate> _conversions; private readonly IDictionary<string, object> _properties;
  • 23. Creazione della pipeline Il Loader: • Crea una istanza di AppBuilder • Identifica la classe di startup • Chiama il metodo Configuration(IAppBuilder app) • Crea una lista ordinata dei componenti con gli associati parametri di creazione • Istanzia i componenti passando a ciascuno il componente successivo e i parametri di creazione.
  • 24. Funzionamento della pipeline La chiamata al primo componente produce l’esecuzione di tutti i componenti della pipeline: Middleware Middleware Middleware Empty Middleware
  • 25. Microsoft Owin: application public class Startup { public void Configuration(IAppBuilder app) { app.Run(context => { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync("Hello, world."); }); } }
  • 26. Costruire un modulo custom public class LoggerMiddleware : OwinMiddleware { private readonly ILog _logger; public LoggerMiddleware(OwinMiddleware next, ILog logger) : base(next) { _logger = logger; } public override async Task Invoke(IOwinContext context) { _logger.LogInfo("Middleware begin"); await this.Next.Invoke(context); _logger.LogInfo("Middleware end"); } }
  • 27. Utilizzare un modulo custom public class Startup { public void Configuration(IAppBuilder appBuilder) { appBuilder.Use<LoggerMiddleware>(new EasyLogger()); ... } }
  • 28. Demo Aggiunta del componente LoggerMiddleware alla pipeline del nostro servizio web.

Editor's Notes

  1. Disabilita le notifiche per 3 ore !!!