SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Downloaden Sie, um offline zu lesen
Middleware   webnextconf - 20152609
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

Más contenido relacionado

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von 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
 

Mehr von 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
 

Último

8 Steps to Build a LangChain RAG Chatbot.
8 Steps to Build a LangChain RAG Chatbot.8 Steps to Build a LangChain RAG Chatbot.
8 Steps to Build a LangChain RAG Chatbot.Ritesh Kanjee
 
Boost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made EasyBoost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made Easymichealwillson701
 
Building Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to startBuilding Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to startMaxim Salnikov
 
renewable energy renewable energy renewable energy renewable energy
renewable energy renewable energy renewable energy  renewable energyrenewable energy renewable energy renewable energy  renewable energy
renewable energy renewable energy renewable energy renewable energyjeyasrig
 
Revolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM GridRevolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM GridMathew Thomas
 
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...telebusocialmarketin
 
Unlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insightsUnlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insightsconfluent
 
8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdf8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdfOffsiteNOC
 
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfFlutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfMind IT Systems
 
Technical improvements. Reasons. Methods. Estimations. CJ
Technical improvements.  Reasons. Methods. Estimations. CJTechnical improvements.  Reasons. Methods. Estimations. CJ
Technical improvements. Reasons. Methods. Estimations. CJpolinaucc
 
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxCYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxBarakaMuyengi
 
Einstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdfEinstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdfCloudMetic
 
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...jackiepotts6
 
Enterprise Content Managements Solutions
Enterprise Content Managements SolutionsEnterprise Content Managements Solutions
Enterprise Content Managements SolutionsIQBG inc
 
MinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young EntrepreneurMinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young EntrepreneurPriyadarshini T
 
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...Splashtop Inc
 
Mobile App Development company Houston
Mobile  App  Development  company HoustonMobile  App  Development  company Houston
Mobile App Development company Houstonjennysmithusa549
 
Steps to Successfully Hire Ionic Developers
Steps to Successfully Hire Ionic DevelopersSteps to Successfully Hire Ionic Developers
Steps to Successfully Hire Ionic Developersmichealwillson701
 
BATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data MeshBATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data MeshBATbern
 

Último (20)

8 Steps to Build a LangChain RAG Chatbot.
8 Steps to Build a LangChain RAG Chatbot.8 Steps to Build a LangChain RAG Chatbot.
8 Steps to Build a LangChain RAG Chatbot.
 
Boost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made EasyBoost Efficiency: Sabre API Integration Made Easy
Boost Efficiency: Sabre API Integration Made Easy
 
Building Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to startBuilding Generative AI-infused apps: what's possible and how to start
Building Generative AI-infused apps: what's possible and how to start
 
renewable energy renewable energy renewable energy renewable energy
renewable energy renewable energy renewable energy  renewable energyrenewable energy renewable energy renewable energy  renewable energy
renewable energy renewable energy renewable energy renewable energy
 
Revolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM GridRevolutionize Your Field Service Management with FSM Grid
Revolutionize Your Field Service Management with FSM Grid
 
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
Telebu Social -Whatsapp Business API : Mastering Omnichannel Business Communi...
 
20140812 - OBD2 Solution
20140812 - OBD2 Solution20140812 - OBD2 Solution
20140812 - OBD2 Solution
 
Unlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insightsUnlocking the Power of IoT: A comprehensive approach to real-time insights
Unlocking the Power of IoT: A comprehensive approach to real-time insights
 
8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdf8 key point on optimizing web hosting services in your business.pdf
8 key point on optimizing web hosting services in your business.pdf
 
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdfFlutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
Flutter the Future of Mobile App Development - 5 Crucial Reasons.pdf
 
Technical improvements. Reasons. Methods. Estimations. CJ
Technical improvements.  Reasons. Methods. Estimations. CJTechnical improvements.  Reasons. Methods. Estimations. CJ
Technical improvements. Reasons. Methods. Estimations. CJ
 
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptxCYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
CYBER SECURITY AND CYBER CRIME COMPLETE GUIDE.pLptx
 
Einstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdfEinstein Copilot Conversational AI for your CRM.pdf
Einstein Copilot Conversational AI for your CRM.pdf
 
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
03.2024_North America VMUG Optimizing RevOps using the power of ChatGPT in Ma...
 
Enterprise Content Managements Solutions
Enterprise Content Managements SolutionsEnterprise Content Managements Solutions
Enterprise Content Managements Solutions
 
MinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young EntrepreneurMinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
MinionLabs_Mr. Gokul Srinivas_Young Entrepreneur
 
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
Splashtop Enterprise Brochure - Remote Computer Access and Remote Support Sof...
 
Mobile App Development company Houston
Mobile  App  Development  company HoustonMobile  App  Development  company Houston
Mobile App Development company Houston
 
Steps to Successfully Hire Ionic Developers
Steps to Successfully Hire Ionic DevelopersSteps to Successfully Hire Ionic Developers
Steps to Successfully Hire Ionic Developers
 
BATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data MeshBATbern52 Swisscom's Journey into Data Mesh
BATbern52 Swisscom's Journey into Data Mesh
 

Middleware webnextconf - 20152609

  • 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