SlideShare a Scribd company logo
1 of 38
Why Middleware?
Christian Horsdal
@chr_horsdal
www.horsdal-consult.dk
About me
Christian Horsdal
Independent Consultant
www.horsdal-consult.dk
c.horsdal@gmail.com
@chr_horsdal
Flexible
Componentized
Reusable
Testable
Web Applications Handle HTTP Requests
5
6
Handler
Log request
Log response
Authenticate
Open DbContext
Close DbContext
Things You Might Do In the Pipeline
Open & dispose resources
Logging
Authentication
Authorization
Quick monitoring endpoints
Sanitize inputs
Content Negotiation
CORS
7
Things You Might Do In the Pipeline
Open & dispose resources
Logging
Authentication
Authorization
Quick monitoring endpoints
Sanitize inputs
Content Negotiation
CORS
8
Cross-cutting concerns
Re-use
Test separately
Update separately
Distribute separately
Do One Thing And Do It Well
9
Compose Pipeline
However You Want
10
11
Handler
Log request
Log response
Authenticate
Open DbContext
Close DbContext
Minify HTML
OWIN
OWIN
• Open Web Interfaces for .NET
• Community driven standard
• Defines mechanics of pipeline
13
OWIN Terminology
Server
The web server
And/or an OWIN adapter
Middleware
Those pieces in the pipeline
Application
The handler
14
No shared assembly
OWIN Terminolgy
16
using AppFunc = Func<IDictionary<string, object>, Task>;
OWIN – Request Environment
Key Name
"owin.RequestBody"
"owin.RequestHeaders"
"owin.RequestMethod"
"owin.RequestPath"
"owin.RequestPathBase"
"owin.RequestProtocol"
"owin.RequestQueryString"
"owin.RequestScheme"
OWIN – Response Environment
Required Key Name
Yes "owin.ResponseBody"
Yes "owin.ResponseHeaders"
No "owin.ResponseStatusCode"
No "owin.ResponseReasonPhrase"
No "owin.ResponseProtocol"
OWIN Terminology
19
using MidFunc = Func<AppFunc, AppFunc>;
Handler
Log request
Log response
Authenticate
Open DbContext
Close DbContext
OWIN “Terminolgy”
20
using BuildFunc = Action<MidFunc>;
No shared assembly
22
OWIN Middleware - As lambda
23
app.UseOwin(buildFunc => buildFunc(next => async ctx =>
{
var stopWatch = new Stopwatch();
stopWatch.Start();
await next(ctx);
WriteLine("Action execution time: " + stopWatch.ElapsedMilliseconds);
}));
OWIN Middleware – As lambda
24
app.UseOwin(buildFunc => buildFunc(next => ctx =>
{
if (ctx["owin.RequestPath"].Equals("/owin-middleware"))
{
var responseText = "Hello World";
var responseBytes = Encoding.UTF8.GetBytes(responseText);
var responseStream = (Stream)ctx["owin.ResponseBody"];
var responseHeaders = (IDictionary<string, string[]>)ctx["owin.ResponseHeaders"];
responseHeaders["Content-Length"] =
new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
responseHeaders["Content-Type"] = new string[] { "text/plain" };
return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length);
}
return next(ctx);
}));
OWIN Middleware – As Class
25
app.UseOwin(buildFunc => buildFunc(next => new PerfLogMiddleware(next).Invoke));
public class PerfLogMiddleware
{
private readonly Func<IDictionary<string, object>, Task> next;
public PerfLogMiddleware(Func<IDictionary<string, object>, Task> next)
{
this.next = next;
}
public async Task Invoke(IDictionary<string, object> ctx)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
await next(ctx);
WriteLine("Action execution time: " + stopWatch.ElapsedMilliseconds);
}
}
ASP.NET 5 Middleware
But, wait. Wasn’t OWIN the middleware thing?
There is a bridge
26
ASP.NET 5 Middleware
27
app.Use(next => async ctx =>
{
if (ctx.Request.Path == "/aspnet-middleware/" )
{
ctx.Response.ContentType = "text/html";
ctx.Response.StatusCode = 200;
await ctx.Response.WriteAsync("Hello Middleware as lambda");
return;
}
await next(ctx);
});
ASP.NET 5 Middleware
28
app.Use(next => new PerfLogAspnetMiddleware(next).Invoke);
private class PerfLogAspnetMiddleware
{
private RequestDelegate next;
public PerfLogAspnetMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext ctx)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
await next(ctx);
WriteLine("Action execution time: " + stopWatch.ElapsedMilliseconds);
}
}
29
OWIN and Web Frameworks
Compatible Frameworks
• ASP.NET MVC 5 & 6
• WebApi
• Nancy
• Simple.Web
30
ASP.NET 5
31
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseOwin();
}
}
ASP.NET < 5 + Katana
32
public class Startup
{
public void Configuration(IAppBuilder builder)
{
builder.Use(new MidFunc(next => (AppFunc)Invoke));
}
public Task Invoke(IDictionary<string, object> environment)
{
…
}
}
Katana
33
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Run(Invoke);
}
public Task Invoke(IOwinContext context)
{
context.Response.ContentType = "text/plain";
return context.Response.WriteAsync("Hello World");
}
}
WebApi + Katana
34
Katana startup.cs code
public class Startup
{
public void Configuration(IAppBuilder builder)
{
HttpConfiguration config = new HttpConfiguration();
config.Routes
.MapHttpRoute("Default", "{controller}/{id}",
new { controller = "Home", id = RouteParameter.O
config.Formatters.XmlFormatter.UseXmlSerializer = true;
config.Formatters.Remove(config.Formatters.JsonFormatter);
builder.UseWebApi(config);
}
}
OWIN Testing
Integration test the complete pipeline
Integration test parts of the pipeline
While in process
35
36
Handler
Log request
Log response
Authenticate
Open DbContext
Close DbContext
Minify HTML
Christian Horsdal
@chr_horsdal
www.horsdal-consult.dk
webnextconf.eu

More Related Content

What's hot

NYAN Conference: Debugging asynchronous scenarios in .net
NYAN Conference: Debugging asynchronous scenarios in .netNYAN Conference: Debugging asynchronous scenarios in .net
NYAN Conference: Debugging asynchronous scenarios in .netAlexandra Hayere
 
Monitoring at scale: Migrating to Prometheus at Fastly
Monitoring at scale: Migrating to Prometheus at FastlyMonitoring at scale: Migrating to Prometheus at Fastly
Monitoring at scale: Migrating to Prometheus at FastlyMarcus Barczak
 
Open Source and Secure Coding Practices
Open Source and Secure Coding PracticesOpen Source and Secure Coding Practices
Open Source and Secure Coding PracticesAll Things Open
 
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...Ontico
 
Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Richard Langlois P. Eng.
 
Android getting started
Android getting startedAndroid getting started
Android getting startedUptech
 
What's new in c# 10
What's new in c# 10What's new in c# 10
What's new in c# 10Moaid Hathot
 
Cfgmgmt Challenges aren't technical anymore
Cfgmgmt Challenges aren't technical anymoreCfgmgmt Challenges aren't technical anymore
Cfgmgmt Challenges aren't technical anymoreJulien Pivotto
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingPraveen Prajapati
 
JDD2015: Kubernetes - Beyond the basics - Paul Bakker
JDD2015: Kubernetes - Beyond the basics - Paul BakkerJDD2015: Kubernetes - Beyond the basics - Paul Bakker
JDD2015: Kubernetes - Beyond the basics - Paul BakkerPROIDEA
 
Client server part 12
Client server part 12Client server part 12
Client server part 12fadlihulopi
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011telestax
 
OpenStack Contribution Workflow
OpenStack Contribution WorkflowOpenStack Contribution Workflow
OpenStack Contribution WorkflowSean McGinnis
 
Heptio Contour - talk CNCF Nantes
Heptio Contour - talk CNCF NantesHeptio Contour - talk CNCF Nantes
Heptio Contour - talk CNCF NantesGaëlle Acas
 

What's hot (20)

NYAN Conference: Debugging asynchronous scenarios in .net
NYAN Conference: Debugging asynchronous scenarios in .netNYAN Conference: Debugging asynchronous scenarios in .net
NYAN Conference: Debugging asynchronous scenarios in .net
 
Monitoring at scale: Migrating to Prometheus at Fastly
Monitoring at scale: Migrating to Prometheus at FastlyMonitoring at scale: Migrating to Prometheus at Fastly
Monitoring at scale: Migrating to Prometheus at Fastly
 
HTTP/2 Server Push
HTTP/2 Server PushHTTP/2 Server Push
HTTP/2 Server Push
 
Retro vs volley (2)
Retro vs volley (2)Retro vs volley (2)
Retro vs volley (2)
 
Open Source and Secure Coding Practices
Open Source and Secure Coding PracticesOpen Source and Secure Coding Practices
Open Source and Secure Coding Practices
 
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
 
Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5Reactive Programming in Java and Spring Framework 5
Reactive Programming in Java and Spring Framework 5
 
Network programming1
Network programming1Network programming1
Network programming1
 
Android getting started
Android getting startedAndroid getting started
Android getting started
 
Reactive Spring Framework 5
Reactive Spring Framework 5Reactive Spring Framework 5
Reactive Spring Framework 5
 
Retrofit
RetrofitRetrofit
Retrofit
 
What's new in c# 10
What's new in c# 10What's new in c# 10
What's new in c# 10
 
Cfgmgmt Challenges aren't technical anymore
Cfgmgmt Challenges aren't technical anymoreCfgmgmt Challenges aren't technical anymore
Cfgmgmt Challenges aren't technical anymore
 
C# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programmingC# 5 deep drive into asynchronous programming
C# 5 deep drive into asynchronous programming
 
JDD2015: Kubernetes - Beyond the basics - Paul Bakker
JDD2015: Kubernetes - Beyond the basics - Paul BakkerJDD2015: Kubernetes - Beyond the basics - Paul Bakker
JDD2015: Kubernetes - Beyond the basics - Paul Bakker
 
Roslyn: el futuro de C#
Roslyn: el futuro de C#Roslyn: el futuro de C#
Roslyn: el futuro de C#
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
CDI Telco Framework & Arquillian presentation at Mobicents Summit, Sochi 2011
 
OpenStack Contribution Workflow
OpenStack Contribution WorkflowOpenStack Contribution Workflow
OpenStack Contribution Workflow
 
Heptio Contour - talk CNCF Nantes
Heptio Contour - talk CNCF NantesHeptio Contour - talk CNCF Nantes
Heptio Contour - talk CNCF Nantes
 

Similar to Middleware webnextconf - 20152609

Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.liKaran Parikh
 
Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...
Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...
Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...Amazon Web Services
 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPMykola Novik
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Codemotion
 
A Brief History of OWIN
A Brief History of OWINA Brief History of OWIN
A Brief History of OWINRyan Riley
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformLucio Grenzi
 
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexusMicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexusEmily Jiang
 
Building a web application with ontinuation monads
Building a web application with ontinuation monadsBuilding a web application with ontinuation monads
Building a web application with ontinuation monadsSeitaro Yuuki
 
Open stack ocata summit enabling aws lambda-like functionality with openstac...
Open stack ocata summit  enabling aws lambda-like functionality with openstac...Open stack ocata summit  enabling aws lambda-like functionality with openstac...
Open stack ocata summit enabling aws lambda-like functionality with openstac...Shaun Murakami
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinGavin Pickin
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with javaDPC Consulting Ltd
 
Innovate2014 Better Integrations Through Open Interfaces
Innovate2014 Better Integrations Through Open InterfacesInnovate2014 Better Integrations Through Open Interfaces
Innovate2014 Better Integrations Through Open InterfacesSteve Speicher
 
Android httpclient
Android httpclientAndroid httpclient
Android httpclientallanh0526
 

Similar to Middleware webnextconf - 20152609 (20)

Campus days 2014 owin
Campus days 2014 owinCampus days 2014 owin
Campus days 2014 owin
 
Owin
OwinOwin
Owin
 
Philly Tech Fest Iis
Philly Tech Fest IisPhilly Tech Fest Iis
Philly Tech Fest Iis
 
Async servers and clients in Rest.li
Async servers and clients in Rest.liAsync servers and clients in Rest.li
Async servers and clients in Rest.li
 
ASP.NET vNext ANUG 20140817
ASP.NET vNext ANUG 20140817ASP.NET vNext ANUG 20140817
ASP.NET vNext ANUG 20140817
 
Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...
Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...
Integrating Infrastructure as Code into a Continuous Delivery Pipeline | AWS ...
 
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOPHOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
HOW TO DEAL WITH BLOCKING CODE WITHIN ASYNCIO EVENT LOOP
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
 
A Brief History of OWIN
A Brief History of OWINA Brief History of OWIN
A Brief History of OWIN
 
Introduction to Node.JS
Introduction to Node.JSIntroduction to Node.JS
Introduction to Node.JS
 
Owin and Katana
Owin and KatanaOwin and Katana
Owin and Katana
 
Building serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platformBuilding serverless application on the Apache Openwhisk platform
Building serverless application on the Apache Openwhisk platform
 
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexusMicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
MicroProfile, Docker, Kubernetes, Istio and Open Shift lab @dev nexus
 
ColdFusion Internals
ColdFusion InternalsColdFusion Internals
ColdFusion Internals
 
Building a web application with ontinuation monads
Building a web application with ontinuation monadsBuilding a web application with ontinuation monads
Building a web application with ontinuation monads
 
Open stack ocata summit enabling aws lambda-like functionality with openstac...
Open stack ocata summit  enabling aws lambda-like functionality with openstac...Open stack ocata summit  enabling aws lambda-like functionality with openstac...
Open stack ocata summit enabling aws lambda-like functionality with openstac...
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
Microservices and modularity with java
Microservices and modularity with javaMicroservices and modularity with java
Microservices and modularity with java
 
Innovate2014 Better Integrations Through Open Interfaces
Innovate2014 Better Integrations Through Open InterfacesInnovate2014 Better Integrations Through Open Interfaces
Innovate2014 Better Integrations Through Open Interfaces
 
Android httpclient
Android httpclientAndroid httpclient
Android httpclient
 

More from Christian Horsdal

Testing microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptxTesting microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptxChristian Horsdal
 
Scoping microservices.20190917
Scoping microservices.20190917Scoping microservices.20190917
Scoping microservices.20190917Christian Horsdal
 
Event sourcing anug 20190227
Event sourcing anug 20190227Event sourcing anug 20190227
Event sourcing anug 20190227Christian Horsdal
 
Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017Christian Horsdal
 
Lightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NETLightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NETChristian Horsdal
 
Three Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. GoThree Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. GoChristian Horsdal
 
Four .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an HourFour .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an HourChristian Horsdal
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkChristian Horsdal
 
DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010Christian Horsdal
 
DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010Christian Horsdal
 

More from Christian Horsdal (12)

Testing microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptxTesting microservices.ANUG.20230111.pptx
Testing microservices.ANUG.20230111.pptx
 
Scoping microservices.20190917
Scoping microservices.20190917Scoping microservices.20190917
Scoping microservices.20190917
 
Event sourcing anug 20190227
Event sourcing anug 20190227Event sourcing anug 20190227
Event sourcing anug 20190227
 
Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017Consolidating services with middleware - NDC London 2017
Consolidating services with middleware - NDC London 2017
 
Intro to.net core 20170111
Intro to.net core   20170111Intro to.net core   20170111
Intro to.net core 20170111
 
Lightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NETLightweight Approach to Building Web APIs with .NET
Lightweight Approach to Building Web APIs with .NET
 
Three Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. GoThree Other Web Frameworks. All .NET. All OSS. One Hour. Go
Three Other Web Frameworks. All .NET. All OSS. One Hour. Go
 
Four .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an HourFour .NET Web Frameworks in Less Than an Hour
Four .NET Web Frameworks in Less Than an Hour
 
Nancy + rest mow2012
Nancy + rest   mow2012Nancy + rest   mow2012
Nancy + rest mow2012
 
Nancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web FrameworkNancy - A Lightweight .NET Web Framework
Nancy - A Lightweight .NET Web Framework
 
DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010DCI ANUG - 24th November 2010
DCI ANUG - 24th November 2010
 
DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010DCI - ANUG 24th November 2010
DCI - ANUG 24th November 2010
 

Recently uploaded

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 

Recently uploaded (20)

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 

Middleware webnextconf - 20152609

  • 1.
  • 3. About me Christian Horsdal Independent Consultant www.horsdal-consult.dk c.horsdal@gmail.com @chr_horsdal
  • 5. Web Applications Handle HTTP Requests 5
  • 7. Things You Might Do In the Pipeline Open & dispose resources Logging Authentication Authorization Quick monitoring endpoints Sanitize inputs Content Negotiation CORS 7
  • 8. Things You Might Do In the Pipeline Open & dispose resources Logging Authentication Authorization Quick monitoring endpoints Sanitize inputs Content Negotiation CORS 8 Cross-cutting concerns Re-use Test separately Update separately Distribute separately
  • 9. Do One Thing And Do It Well 9
  • 11. 11 Handler Log request Log response Authenticate Open DbContext Close DbContext Minify HTML
  • 12. OWIN
  • 13. OWIN • Open Web Interfaces for .NET • Community driven standard • Defines mechanics of pipeline 13
  • 14. OWIN Terminology Server The web server And/or an OWIN adapter Middleware Those pieces in the pipeline Application The handler 14
  • 16. OWIN Terminolgy 16 using AppFunc = Func<IDictionary<string, object>, Task>;
  • 17. OWIN – Request Environment Key Name "owin.RequestBody" "owin.RequestHeaders" "owin.RequestMethod" "owin.RequestPath" "owin.RequestPathBase" "owin.RequestProtocol" "owin.RequestQueryString" "owin.RequestScheme"
  • 18. OWIN – Response Environment Required Key Name Yes "owin.ResponseBody" Yes "owin.ResponseHeaders" No "owin.ResponseStatusCode" No "owin.ResponseReasonPhrase" No "owin.ResponseProtocol"
  • 19. OWIN Terminology 19 using MidFunc = Func<AppFunc, AppFunc>; Handler Log request Log response Authenticate Open DbContext Close DbContext
  • 22. 22
  • 23. OWIN Middleware - As lambda 23 app.UseOwin(buildFunc => buildFunc(next => async ctx => { var stopWatch = new Stopwatch(); stopWatch.Start(); await next(ctx); WriteLine("Action execution time: " + stopWatch.ElapsedMilliseconds); }));
  • 24. OWIN Middleware – As lambda 24 app.UseOwin(buildFunc => buildFunc(next => ctx => { if (ctx["owin.RequestPath"].Equals("/owin-middleware")) { var responseText = "Hello World"; var responseBytes = Encoding.UTF8.GetBytes(responseText); var responseStream = (Stream)ctx["owin.ResponseBody"]; var responseHeaders = (IDictionary<string, string[]>)ctx["owin.ResponseHeaders"]; responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) }; responseHeaders["Content-Type"] = new string[] { "text/plain" }; return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length); } return next(ctx); }));
  • 25. OWIN Middleware – As Class 25 app.UseOwin(buildFunc => buildFunc(next => new PerfLogMiddleware(next).Invoke)); public class PerfLogMiddleware { private readonly Func<IDictionary<string, object>, Task> next; public PerfLogMiddleware(Func<IDictionary<string, object>, Task> next) { this.next = next; } public async Task Invoke(IDictionary<string, object> ctx) { var stopWatch = new Stopwatch(); stopWatch.Start(); await next(ctx); WriteLine("Action execution time: " + stopWatch.ElapsedMilliseconds); } }
  • 26. ASP.NET 5 Middleware But, wait. Wasn’t OWIN the middleware thing? There is a bridge 26
  • 27. ASP.NET 5 Middleware 27 app.Use(next => async ctx => { if (ctx.Request.Path == "/aspnet-middleware/" ) { ctx.Response.ContentType = "text/html"; ctx.Response.StatusCode = 200; await ctx.Response.WriteAsync("Hello Middleware as lambda"); return; } await next(ctx); });
  • 28. ASP.NET 5 Middleware 28 app.Use(next => new PerfLogAspnetMiddleware(next).Invoke); private class PerfLogAspnetMiddleware { private RequestDelegate next; public PerfLogAspnetMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext ctx) { var stopWatch = new Stopwatch(); stopWatch.Start(); await next(ctx); WriteLine("Action execution time: " + stopWatch.ElapsedMilliseconds); } }
  • 29. 29 OWIN and Web Frameworks
  • 30. Compatible Frameworks • ASP.NET MVC 5 & 6 • WebApi • Nancy • Simple.Web 30
  • 31. ASP.NET 5 31 public class Startup { public void Configure(IApplicationBuilder app) { app.UseOwin(); } }
  • 32. ASP.NET < 5 + Katana 32 public class Startup { public void Configuration(IAppBuilder builder) { builder.Use(new MidFunc(next => (AppFunc)Invoke)); } public Task Invoke(IDictionary<string, object> environment) { … } }
  • 33. Katana 33 public class Startup { public void Configuration(IAppBuilder app) { app.Run(Invoke); } public Task Invoke(IOwinContext context) { context.Response.ContentType = "text/plain"; return context.Response.WriteAsync("Hello World"); } }
  • 34. WebApi + Katana 34 Katana startup.cs code public class Startup { public void Configuration(IAppBuilder builder) { HttpConfiguration config = new HttpConfiguration(); config.Routes .MapHttpRoute("Default", "{controller}/{id}", new { controller = "Home", id = RouteParameter.O config.Formatters.XmlFormatter.UseXmlSerializer = true; config.Formatters.Remove(config.Formatters.JsonFormatter); builder.UseWebApi(config); } }
  • 35. OWIN Testing Integration test the complete pipeline Integration test parts of the pipeline While in process 35
  • 36. 36 Handler Log request Log response Authenticate Open DbContext Close DbContext Minify HTML