SlideShare una empresa de Scribd logo
1 de 21
How to get full power from
         WebApi
        Raffaele Rialdi
          @raffaeler
       http://iamraf.net
Thanks to the sponsors
What is WebApi
                  in one slide
• A library to create HTTP services
   – HTTP is highly scalable (disconnect, cloud, …)
• Designed to create REST services
   – WebApi does not automatically imply REST
   – Use HTTP as an application (not a transport) protocol
• Fits in heterogeneous device/OS scenarios
   – Avoid typical SOAP versioning problems
   – It's highly pluggable
• Leverages the Asp.net MVC 4 model
WebApi is flexible
• oData is a work-in progress
  – look at nightly builds, avoid current pre-release
• Can be Self-Hosted outside IIS and MVC4
  – Easy way for inter-AppDomain or inter-Process
  – Console example:
            var config = new HttpSelfHostConfiguration("http://localhost:8000");

            config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
              new { id = RouteParameter.Optional });

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
               server.OpenAsync().Wait();
               Console.WriteLine("Press any key to exit");
               Console.ReadKey();
            }
THE REQUEST JOURNEY
Routing to a Controller
Request      controller



   • Use the standard MVC Routes
          – extract Controller, Action and parameters
   • Controller selection under the hood
          – IHttpControllerSelector.SelectController
             • HttpRequestMessage  HttpControllerDescriptor
   • Plug-in Controllers using IDependencyResolver
          – Nuget has a lot of ready to use IoC containers
Selecting an Action
Request      controller      action


   • The easiest way is to modify the default Route
    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );                             config.Routes.MapHttpRoute(
                                   name: "DefaultApi2",
                                   routeTemplate: "api/{controller}/{action}/{x}/{y}" );

   • Can use [ActionName("myaction")]
          – override the method name as the action name
   • Can use [NonAction]
          – exclude a method from being an action
Selecting an Action by code
Request      controller   action


   • Derive ApiControllerActionSelector            Use case:
          – override SelectAction                  Versioning!


   • Implement IHttpActionSelector
          – Implement SelectAction
          – Obtain the previous selector in ctor
          – Call previous selector

   • In SelectAction method:
          – in: HttpControllerContext
          – out: HttpActionDescription
Authorization filter
Request         controller        action         authoriz.                           I’ll play with
                                                                                          Claims

   •      [Authorize] is Role oriented
   •      Derive AuthorizeAttribute to go Claim oriented
   •      [AllowAnonymous] is self-explanatory
   •      Starting from Fx4.5 new universal base classes
          – ClaimsPrincipal for every Principal
          – ClaimsIdentity for every Identity



           IPrincipal client = Thread.CurrentPrincipal;


           ClaimsPrincipal principal = Thread.CurrentPrincipal as ClaimsPrincipal;
           ClaimsIdentity identity = principal.Identity as ClaimsIdentity;
Security considerations
• WebApi authorization model is not built-in
  – AuthorizationFilters / MessageHandlers are used
    to plugin the desired mechanism
  – Per-route handlers gives finer control


• Use Filters/Handlers to add/modify claims
Model Bind
Request      controller   action      authoriz.   binding



   • IValueProvider (Bind3 example)
          – useful to populate an action parameter
          – Require a ValueProviderFactory (applied via attribute)
   • HttpParameterBinding (Bind4 example)
          – Associate a type to a provider
   • IActionValueBinder (Bind5 example)
          – Associate an HttpActionDescription to a provider
   • DefaultActionValueBinder (Bind6 example)
          – Intercept default provider
   • IModelBinder (Bind7 example)
          – Execute the binding. Must provide the value
Action Filters
                                                         action
Request      controller   action   authoriz.   binding    filter



   • Called before and after the action execution

                                                               Use case:
   • Implement IActionFilter                                   validation &
                                                               auditing!
          or better….
   • Derive ActionFilterAttribute
          – OnActionExecuting
          – OnActionExecuted
Target was reached!
                                                             action     invoke
Request      controller    action   authoriz.    binding      filter    action



   • In the action we have different options:
          – return an entity that will be embedded in a response
          – build and return the HttpResponseMessage
             • Can be an error (no exceptions imply better performances)
          or
          – throw a CLR exception (a filter will convert it in a msg)
          – throw an HttpResponseException
             • returns the HTTP status code of your choice
             • it's a full response (specify Content, Headers, ReasonPhrase)
HttpError
• Nice way to create the error message
    – Errors flow in the same way of the content
    – Keys/Values can be added for additional infos
 var msg = string.Format("Product with id = {0} not found", id);
 HttpError err = new HttpError(msg);
 return Request.CreateResponse(HttpStatusCode.NotFound, err);

 var msg = string.Format("Product with id = {0} not found", id);
 return Request.CreateErrorResponse(HttpStatusCode.NotFound, msg);


 HTTP/1.1 404 Not Found
 Content-Type: application/json; charset=utf-8
 Date: Thu, 09 Aug 2012 23:27:18 GMT
 Content-Length: 51

 { "Message": "Product with id = 12 not found" }
Action filter
                                 action    invoke
                                  filter   action



• Same filter of the request
• OnActionExecuted
Exception Filters
                                 exception   action     invoke
                                   filter     filter    action



• Do not use MVC [HandleError]
• Transform CLR exceptions in HTTP messages
• Implement IExceptionFilter or better derive
  ExceptionFilterAttribute
• Mark actions with the attribute
      or
• Change the global configuration
  – GlobalConfiguration.Configuration.Filters.Add(new
    MyNamespace.NotImplExceptionFilterAttribute());
Formatting data for the output
                                      exception   action    invoke
              Response   formatting                         action
                                        filter     filter



• MediaTypeFormatter is the abstract base class
  to serialize entities in whatever format
• Built-in formatters:
  – Json.net and Xml formatter are built-in
  – bson and many others on nuget
  – your own just deriving this class
• The correct formatter is picked up upon "http
  content negotiation"
GOING DEEPER
Message Handlers
  Request                custom       Http         Http
            HttpServer   Message    Routing     Controller   Controller
 Response                Handler   Dispatcher   Dispatcher



• Message Handlers works at the beginning of the
  pipeline
   – They can use the message and pass it over
   – Or can "short-circuit" to the response (early validation)
• MH still don't know the controller, action, etc.
• Every endpoint has different MH instances
• Typical usage:
   – Early validation of the message / headers (security keys)
   – Packet inspection
Wrap up
• Webapi = extreme pluggability
• Just follow the request
  – Before or later it will become a response 



            Questions?
Please rate this session
Scan the code, go online, rate this session

Más contenido relacionado

La actualidad más candente

SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra Sencha
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsLukasz Lysik
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React AppAll Things Open
 
OroCRM Technology Webinar May 28, 2014
OroCRM Technology Webinar May 28, 2014OroCRM Technology Webinar May 28, 2014
OroCRM Technology Webinar May 28, 2014Jary Carter
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6Andy Butland
 
Azure Container Apps
Azure Container AppsAzure Container Apps
Azure Container AppsICS
 
Drupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHPDrupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHPAntonio Peric-Mazar
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9aminmesbahi
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootTrey Howard
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
ASP.NET Web API O to 100
ASP.NET Web API O to 100ASP.NET Web API O to 100
ASP.NET Web API O to 100Himanshu Desai
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakMarcus Denker
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootOmri Spector
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...seleniumconf
 
Declarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleDeclarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleFelix Meschberger
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns Alex Theedom
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...bjhargrave
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17aminmesbahi
 

La actualidad más candente (20)

SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra  SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
SenchaCon 2016: Learn the Top 10 Best ES2015 Features - Lee Boonstra
 
ASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline InternalsASP.NET MVC 4 Request Pipeline Internals
ASP.NET MVC 4 Request Pipeline Internals
 
The Many Ways to Test Your React App
The Many Ways to Test Your React AppThe Many Ways to Test Your React App
The Many Ways to Test Your React App
 
OroCRM Technology Webinar May 28, 2014
OroCRM Technology Webinar May 28, 2014OroCRM Technology Webinar May 28, 2014
OroCRM Technology Webinar May 28, 2014
 
ASP.Net 5 and C# 6
ASP.Net 5 and C# 6ASP.Net 5 and C# 6
ASP.Net 5 and C# 6
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Azure Container Apps
Azure Container AppsAzure Container Apps
Azure Container Apps
 
Drupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHPDrupal8 for Symfony developers - Dutch PHP
Drupal8 for Symfony developers - Dutch PHP
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
ASP.NET Web API O to 100
ASP.NET Web API O to 100ASP.NET Web API O to 100
ASP.NET Web API O to 100
 
Reflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond SmalltakReflection in Pharo: Beyond Smalltak
Reflection in Pharo: Beyond Smalltak
 
Building a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring BootBuilding a REST Service in minutes with Spring Boot
Building a REST Service in minutes with Spring Boot
 
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
Testing Rapidly Changing Applications With Self-Testing Object-Oriented Selen...
 
Declarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi styleDeclarative Services Dependency Injection OSGi style
Declarative Services Dependency Injection OSGi style
 
Java EE revisits design patterns
Java EE revisits design patterns Java EE revisits design patterns
Java EE revisits design patterns
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...
 
.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17.NET Core, ASP.NET Core Course, Session 17
.NET Core, ASP.NET Core Course, Session 17
 
Variables in Pharo5
Variables in Pharo5Variables in Pharo5
Variables in Pharo5
 

Destacado

WebAPI::DBIC - Automated RESTful API's
WebAPI::DBIC - Automated RESTful API'sWebAPI::DBIC - Automated RESTful API's
WebAPI::DBIC - Automated RESTful API'sMichael Francis
 
Ross Boucher - Quality Control: Testing and debugging your apps
Ross Boucher - Quality Control: Testing and debugging your appsRoss Boucher - Quality Control: Testing and debugging your apps
Ross Boucher - Quality Control: Testing and debugging your appsWeb Directions
 
ASP.Net WebAPI經驗分享
ASP.Net WebAPI經驗分享ASP.Net WebAPI經驗分享
ASP.Net WebAPI經驗分享國昭 張
 
Modern Tools for API Testing, Debugging and Monitoring
Modern Tools for API Testing, Debugging and MonitoringModern Tools for API Testing, Debugging and Monitoring
Modern Tools for API Testing, Debugging and MonitoringNeil Mansilla
 
web apiで遊び倒す
web apiで遊び倒すweb apiで遊び倒す
web apiで遊び倒すKeiichi Daiba
 

Destacado (8)

WebAPI::DBIC - Automated RESTful API's
WebAPI::DBIC - Automated RESTful API'sWebAPI::DBIC - Automated RESTful API's
WebAPI::DBIC - Automated RESTful API's
 
Da DotNet a DotNetCore
Da DotNet a DotNetCoreDa DotNet a DotNetCore
Da DotNet a DotNetCore
 
Ross Boucher - Quality Control: Testing and debugging your apps
Ross Boucher - Quality Control: Testing and debugging your appsRoss Boucher - Quality Control: Testing and debugging your apps
Ross Boucher - Quality Control: Testing and debugging your apps
 
ASP.Net WebAPI經驗分享
ASP.Net WebAPI經驗分享ASP.Net WebAPI經驗分享
ASP.Net WebAPI經驗分享
 
Modern Tools for API Testing, Debugging and Monitoring
Modern Tools for API Testing, Debugging and MonitoringModern Tools for API Testing, Debugging and Monitoring
Modern Tools for API Testing, Debugging and Monitoring
 
web apiで遊び倒す
web apiで遊び倒すweb apiで遊び倒す
web apiで遊び倒す
 
Presentation on operating system
 Presentation on operating system Presentation on operating system
Presentation on operating system
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
 

Similar a How to get full power from WebApi

Advance java session 17
Advance java session 17Advance java session 17
Advance java session 17Smita B Kumar
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...WordCamp Sydney
 
ASP.NET MVC 2.0
ASP.NET MVC 2.0ASP.NET MVC 2.0
ASP.NET MVC 2.0Buu Nguyen
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIKevin Hazzard
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAnthony Ferrari
 
API Testing with Open Source Code and Cucumber
API Testing with Open Source Code and CucumberAPI Testing with Open Source Code and Cucumber
API Testing with Open Source Code and CucumberSmartBear
 
Sling Component Filters in CQ5
Sling Component Filters in CQ5 Sling Component Filters in CQ5
Sling Component Filters in CQ5 connectwebex
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdfArumugam90
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsitricks
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...WebStackAcademy
 

Similar a How to get full power from WebApi (20)

Advance java session 17
Advance java session 17Advance java session 17
Advance java session 17
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
 
ASP.NET MVC 2.0
ASP.NET MVC 2.0ASP.NET MVC 2.0
ASP.NET MVC 2.0
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
 
Filter
FilterFilter
Filter
 
Filter
FilterFilter
Filter
 
API Check Overview - Rigor Monitoring
API Check Overview - Rigor MonitoringAPI Check Overview - Rigor Monitoring
API Check Overview - Rigor Monitoring
 
API Testing with Open Source Code and Cucumber
API Testing with Open Source Code and CucumberAPI Testing with Open Source Code and Cucumber
API Testing with Open Source Code and Cucumber
 
Sling Component Filters in CQ5
Sling Component Filters in CQ5 Sling Component Filters in CQ5
Sling Component Filters in CQ5
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Making the most out of CakePHP 2.2
Making the most out of CakePHP 2.2Making the most out of CakePHP 2.2
Making the most out of CakePHP 2.2
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Servlets
ServletsServlets
Servlets
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 

Último

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Último (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

How to get full power from WebApi

  • 1. How to get full power from WebApi Raffaele Rialdi @raffaeler http://iamraf.net
  • 2. Thanks to the sponsors
  • 3. What is WebApi in one slide • A library to create HTTP services – HTTP is highly scalable (disconnect, cloud, …) • Designed to create REST services – WebApi does not automatically imply REST – Use HTTP as an application (not a transport) protocol • Fits in heterogeneous device/OS scenarios – Avoid typical SOAP versioning problems – It's highly pluggable • Leverages the Asp.net MVC 4 model
  • 4. WebApi is flexible • oData is a work-in progress – look at nightly builds, avoid current pre-release • Can be Self-Hosted outside IIS and MVC4 – Easy way for inter-AppDomain or inter-Process – Console example: var config = new HttpSelfHostConfiguration("http://localhost:8000"); config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); using (HttpSelfHostServer server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
  • 6. Routing to a Controller Request controller • Use the standard MVC Routes – extract Controller, Action and parameters • Controller selection under the hood – IHttpControllerSelector.SelectController • HttpRequestMessage  HttpControllerDescriptor • Plug-in Controllers using IDependencyResolver – Nuget has a lot of ready to use IoC containers
  • 7. Selecting an Action Request controller action • The easiest way is to modify the default Route config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi2", routeTemplate: "api/{controller}/{action}/{x}/{y}" ); • Can use [ActionName("myaction")] – override the method name as the action name • Can use [NonAction] – exclude a method from being an action
  • 8. Selecting an Action by code Request controller action • Derive ApiControllerActionSelector Use case: – override SelectAction Versioning! • Implement IHttpActionSelector – Implement SelectAction – Obtain the previous selector in ctor – Call previous selector • In SelectAction method: – in: HttpControllerContext – out: HttpActionDescription
  • 9. Authorization filter Request controller action authoriz. I’ll play with Claims • [Authorize] is Role oriented • Derive AuthorizeAttribute to go Claim oriented • [AllowAnonymous] is self-explanatory • Starting from Fx4.5 new universal base classes – ClaimsPrincipal for every Principal – ClaimsIdentity for every Identity IPrincipal client = Thread.CurrentPrincipal; ClaimsPrincipal principal = Thread.CurrentPrincipal as ClaimsPrincipal; ClaimsIdentity identity = principal.Identity as ClaimsIdentity;
  • 10. Security considerations • WebApi authorization model is not built-in – AuthorizationFilters / MessageHandlers are used to plugin the desired mechanism – Per-route handlers gives finer control • Use Filters/Handlers to add/modify claims
  • 11. Model Bind Request controller action authoriz. binding • IValueProvider (Bind3 example) – useful to populate an action parameter – Require a ValueProviderFactory (applied via attribute) • HttpParameterBinding (Bind4 example) – Associate a type to a provider • IActionValueBinder (Bind5 example) – Associate an HttpActionDescription to a provider • DefaultActionValueBinder (Bind6 example) – Intercept default provider • IModelBinder (Bind7 example) – Execute the binding. Must provide the value
  • 12. Action Filters action Request controller action authoriz. binding filter • Called before and after the action execution Use case: • Implement IActionFilter validation & auditing! or better…. • Derive ActionFilterAttribute – OnActionExecuting – OnActionExecuted
  • 13. Target was reached! action invoke Request controller action authoriz. binding filter action • In the action we have different options: – return an entity that will be embedded in a response – build and return the HttpResponseMessage • Can be an error (no exceptions imply better performances) or – throw a CLR exception (a filter will convert it in a msg) – throw an HttpResponseException • returns the HTTP status code of your choice • it's a full response (specify Content, Headers, ReasonPhrase)
  • 14. HttpError • Nice way to create the error message – Errors flow in the same way of the content – Keys/Values can be added for additional infos var msg = string.Format("Product with id = {0} not found", id); HttpError err = new HttpError(msg); return Request.CreateResponse(HttpStatusCode.NotFound, err); var msg = string.Format("Product with id = {0} not found", id); return Request.CreateErrorResponse(HttpStatusCode.NotFound, msg); HTTP/1.1 404 Not Found Content-Type: application/json; charset=utf-8 Date: Thu, 09 Aug 2012 23:27:18 GMT Content-Length: 51 { "Message": "Product with id = 12 not found" }
  • 15. Action filter action invoke filter action • Same filter of the request • OnActionExecuted
  • 16. Exception Filters exception action invoke filter filter action • Do not use MVC [HandleError] • Transform CLR exceptions in HTTP messages • Implement IExceptionFilter or better derive ExceptionFilterAttribute • Mark actions with the attribute or • Change the global configuration – GlobalConfiguration.Configuration.Filters.Add(new MyNamespace.NotImplExceptionFilterAttribute());
  • 17. Formatting data for the output exception action invoke Response formatting action filter filter • MediaTypeFormatter is the abstract base class to serialize entities in whatever format • Built-in formatters: – Json.net and Xml formatter are built-in – bson and many others on nuget – your own just deriving this class • The correct formatter is picked up upon "http content negotiation"
  • 19. Message Handlers Request custom Http Http HttpServer Message Routing Controller Controller Response Handler Dispatcher Dispatcher • Message Handlers works at the beginning of the pipeline – They can use the message and pass it over – Or can "short-circuit" to the response (early validation) • MH still don't know the controller, action, etc. • Every endpoint has different MH instances • Typical usage: – Early validation of the message / headers (security keys) – Packet inspection
  • 20. Wrap up • Webapi = extreme pluggability • Just follow the request – Before or later it will become a response  Questions?
  • 21. Please rate this session Scan the code, go online, rate this session

Notas del editor

  1. high perf