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

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
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
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
(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
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 

Recently uploaded (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
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...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
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
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
(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...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 

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