SlideShare a Scribd company logo
1 of 37
ASP.NET Web API
Extensibility

 Eyal Vardi
 CEO E4D Solutions LTD
 Microsoft MVP Visual C#
 blog: www.eVardi.com
Expert Days 2012
                                                                                 




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Agenda




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Web API Configuration




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Configuring ASP.NET Web API
           Global Configuration Settings (ASP.NET Hosting)
           Global Configuration Settings (Self-Hosting)
           Services
           Per-Controller Configuration




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Global Configuration Settings
   (ASP.NET Hosting)

           Stored in the GlobalConfiguration object,
            which is contains a singleton
            HttpConfiguration instance.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HttpConfiguration
     Member                     Description

     DependencyResolver         Enables dependency injection for controllers.

     Filters                    Action filters.
     Formatters                 Media-type formatters.

                                Specifies whether the server should include error details, such as
     IncludeErrorDetailPolicy
                                exception messages and stack traces, in HTTP response messages.

     Initializer                A function that performs final initialization of the HttpConfiguration.

     MessageHandlers            HTTP message handlers.

     ParameterBindingRules      A collection of rules for binding parameters on controller actions.

     Properties                 A generic property bag.

     Routes                     The collection of routes
     Services                   The collection of services.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
WebApiConfig
           The call to WebApiConfig.Register configures
            Web API. The definition for the WebApiConfig
            class is located in the App_Start directory.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Global Configuration Settings
   (Self-Hosting)
           If you self-host Web API, the configuration
            settings are stored in the
            HttpSelfHostConfiguration class, which
            derives from HttpConfiguration.

             var config = new HttpSelfHostConfiguration("http://localhost:8080");

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

             // Add a media-type formatter
             config.Formatters.Add(new MyFormatter());



© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Services
           The HttpConfiguration.Services collection
            contains a set of global services that Web API
            uses to perform various tasks.
                  Controller selection (IHttpControllerSelector)
                  Content negotiation (IContentNegotiator)
                  IActionValueBinder
                  IApiExplorer
                  IAssembliesResolver
                  IBodyModelValidator
                  IDocumentationProvider
                  IHttpActionInvoker
                  IHttpControllerTypeResolver
                  ITraceManager & ITraceWriter
                  …
© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Per-Controller Configuration
           You can override per controller
                  Media-type formatters
                  Parameter binding rules
                  Services

      public class ControllerConfigAttribute : Attribute, IControllerConfiguration
      {
          public void Initialize(HttpControllerSettings settings,
              HttpControllerDescriptor descriptor)
          {
              // Remove the JSON formatter.
              var jsonFormatter = settings.Formatters.JsonFormatter;
              settings.Formatters.Remove(jsonFormatter);

                // Add a custom media-type formatter.
                settings.Formatters.Add(new MyFormatter());

                // Add a custom action selector.
                settings.Services.Replace(typeof(IHttpActionSelector), new MyActionSelector());
           }
      }


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Routing




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Routing Tables
            routes.MapHttpRoute(
                   name:                       "DefaultApi",
                   routeTemplate:              "api/{controller}/{id}",
                   defaults:                   new { id = RouteParameter.Optional }
                   constraints:                new { id = @"d+" }

            );




                         Action                       HTTP method                        Relative URI
         Get a list of all products                   GET                        /api/products
         Get a product by ID                          GET                        /api/products/id

         Get a product by category                    GET                        /api/products?category=1



© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Selecting a Controller
           Controller selection is handled by the
            IHttpControllerSelector.SelectController
            method.
           This method takes an HttpRequestMessage
            instance and returns an HttpControllerDescriptor.
           The default implementation is provided by the
            DefaultHttpControllerSelector class.
            1.     Look in the route dictionary for the key "controller".

            2.     Take the value for this key and append the string "Controller"
                   to get the controller type name.

            3.     Look for a Web API controller with this type name.

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Selecting a Controller
           For step 3, DefaultHttpControllerSelector uses
            the IHttpControllerTypeResolver interface to
            get the list of Web API controller types.

           The default implementation of
            IHttpControllerTypeResolver returns all public
            classes that:
                  Implement IHttpController,
                  Not abstract
                  Have a name that ends in "Controller".




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Selecting a Controller




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Selecting a Controller


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Action Selection
           Action selection done by calling the
            IHttpActionSelector.SelectAction
            method.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Action Selection
           The default implementation is provided by the
            ApiControllerActionSelector class. To select
            an action, it looks at the following:
                  The HTTP method of the request.

                  The "{action}" placeholder in the route template, if present.

                  The parameters of the actions on the controller.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Action Selection Algorithm
    1.      Create a list of all actions on the controller that match
            the HTTP request method.
    2.      If the route dictionary has an "action" entry, remove
            actions whose name does not match this value.
    3.      Try to match action parameters to the URI, as follows:
            1.     For each action, get a list of the parameters that are a simple type,
                   where the binding gets the parameter from the URI. Exclude
                   optional parameters.
            2.     From this list, try to find a match for each parameter name, either in
                   the route dictionary or in the URI query string. Matches are case
                   insensitive and do not depend on the parameter order.
            3.     Select an action where every parameter in the list has a match in the
                   URI.
            4.     If more that one action meets these criteria, pick the one with the
                   most parameter matches.
    4.      Ignore actions with the [NonAction] attribute.
© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Action Selection


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HTTP Message Handlers




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HTTP Message Handlers
           HttpRequestMessage
            represents the HTTP request.

           HttpResponseMessage
            represents the HTTP response.

           HttpMessageHandler
            objects process the request and response




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Client




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Server
           HttpServer derives from HttpMessageHandler.
                  The request then passes through a series of message
                   handlers.


           HttpControllerDispatcher handler uses the
            routing table to route the request to a Web API
            controller.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HTTP Request in Memory
        var config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
               "default",
               "api/{controller}/{id}",
               new { id = RouteParameter.Optional });

        HttpServer server = new HttpServer(config);

        // Connect client directly to server
        HttpClient client = new HttpClient(server);

        var response = client.GetAsync("http://anything/api/products").Result;




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Custom Message Handlers
           Process the request message.
           Call base.SendAsync to send the message to
            the inner handler. This step is asynchronous.
           Process the response message and return it
            to the caller.

                            Task<HttpResponseMessage> SendAsync(
                                HttpRequestMessage request,
                                CancellationToken cancellationToken);




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Custom Response Header
      public class CustomHeaderHandler : DelegatingHandler
      {
          protected override Task<HttpResponseMessage> SendAsync(
              HttpRequestMessage request, CancellationToken cancellationToken)
          {
              return base.SendAsync(request, cancellationToken)
                         .ContinueWith(
                               (task) =>
                               {
                                   HttpResponseMessage response = task.Result;
                                   response.Headers.Add(
                                       "X-Custom-Header",
                                       "This is my custom header.");
                                   return response;
                               }
                           );
          }
      }



© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Custom Message
          Handlers

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Formats & Model Binding




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Internet Media Types
           A media type, also called a MIME type.
                  Identifies the format of a piece of data.
                  Describe the format of the message body.
                  A media type consists of two strings, a type and a subtype.
                   For example:
                     text/html
                     image/png
                     application/json


                            HTTP/1.1 200 OK
                            Content-Length: 95267
                            Content-Type: image/png
                            Accept: text/html,application/xhtml+xml



© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Media Formatter
           In Web API, the media type determines how
            Web API serializes and deserializes the HTTP
            message body.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Custom Media
          Formatter

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Exceptions




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Exception Handling
           By default, most exceptions are translated into an
            HTTP response with status code 500, Internal Server
            Error.
           For example, the following method returns 404, Not
            Found, if the id parameter is not valid.

            public Product GetProduct(int id)
            {
                Product item = repository.Get(id);
                if (item == null)
                {
                    throw new HttpResponseException(
                            new HttpResponseMessage( HttpStatusCode.NotFound ));
                }
                return item;
            }

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Exception Filters
           An exception filter is executed when a
            controller method throws any unhandled
            exception that is not an HttpResponseException
            exception.
    NotImplementedException exceptions into HTTP status code 501, Not Implemented.
        public class NotImplExceptionFilter : ExceptionFilterAttribute
        {
            public override void OnException(HttpActionExecutedContext context)
            {
               if (context.Exception is NotImplementedException)
               {
                  context.Response =
                        new HttpResponseMessage(HttpStatusCode.NotImplemented);
                }
            }
        }

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Exception Filters


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

More Related Content

Similar to Asp.net web api extensibility

Document_format_for_OData_In_A_Nutshell.pdf
Document_format_for_OData_In_A_Nutshell.pdfDocument_format_for_OData_In_A_Nutshell.pdf
Document_format_for_OData_In_A_Nutshell.pdfdavidjpeace
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Tim Burks
 
Joget Workflow v6 Training Slides - 18 - Integrating with External System
Joget Workflow v6 Training Slides - 18 - Integrating with External SystemJoget Workflow v6 Training Slides - 18 - Integrating with External System
Joget Workflow v6 Training Slides - 18 - Integrating with External SystemJoget Workflow
 
TechEvent Eclipse Microprofile
TechEvent Eclipse MicroprofileTechEvent Eclipse Microprofile
TechEvent Eclipse MicroprofileTrivadis
 
Protocol
ProtocolProtocol
Protocolm_bahba
 
Wcf data services
Wcf data servicesWcf data services
Wcf data servicesEyal Vardi
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
Ektron CMS400 8.02
Ektron CMS400 8.02Ektron CMS400 8.02
Ektron CMS400 8.02Alpesh Patel
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01raviIITRoorkee
 
There is time for rest
There is time for rest There is time for rest
There is time for rest SoftServe
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaJignesh Aakoliya
 
MuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and ODataMuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and ODataPace Integration
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
Odata introduction
Odata introductionOdata introduction
Odata introductionAhmad Dwedar
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Mindfire Solutions
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Mike Taulty OData (NxtGen User Group UK)
Mike Taulty OData (NxtGen User Group UK)Mike Taulty OData (NxtGen User Group UK)
Mike Taulty OData (NxtGen User Group UK)ukdpe
 
10 Ace 2010 Aras Federation Workshop
10 Ace 2010 Aras Federation Workshop10 Ace 2010 Aras Federation Workshop
10 Ace 2010 Aras Federation WorkshopProdeos
 

Similar to Asp.net web api extensibility (20)

Document_format_for_OData_In_A_Nutshell.pdf
Document_format_for_OData_In_A_Nutshell.pdfDocument_format_for_OData_In_A_Nutshell.pdf
Document_format_for_OData_In_A_Nutshell.pdf
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)
 
Joget Workflow v6 Training Slides - 18 - Integrating with External System
Joget Workflow v6 Training Slides - 18 - Integrating with External SystemJoget Workflow v6 Training Slides - 18 - Integrating with External System
Joget Workflow v6 Training Slides - 18 - Integrating with External System
 
TechEvent Eclipse Microprofile
TechEvent Eclipse MicroprofileTechEvent Eclipse Microprofile
TechEvent Eclipse Microprofile
 
Protocol
ProtocolProtocol
Protocol
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
 
Spring training
Spring trainingSpring training
Spring training
 
Ektron CMS400 8.02
Ektron CMS400 8.02Ektron CMS400 8.02
Ektron CMS400 8.02
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
 
There is time for rest
There is time for rest There is time for rest
There is time for rest
 
Overview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company indiaOverview of MVC Framework - by software outsourcing company india
Overview of MVC Framework - by software outsourcing company india
 
MuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and ODataMuleSoft London Community February 2020 - MuleSoft and OData
MuleSoft London Community February 2020 - MuleSoft and OData
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Odata introduction
Odata introductionOdata introduction
Odata introduction
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Mike Taulty OData (NxtGen User Group UK)
Mike Taulty OData (NxtGen User Group UK)Mike Taulty OData (NxtGen User Group UK)
Mike Taulty OData (NxtGen User Group UK)
 
RIA and Ajax
RIA and AjaxRIA and Ajax
RIA and Ajax
 
10 Ace 2010 Aras Federation Workshop
10 Ace 2010 Aras Federation Workshop10 Ace 2010 Aras Federation Workshop
10 Ace 2010 Aras Federation Workshop
 

More from Eyal Vardi

Smart Contract
Smart ContractSmart Contract
Smart ContractEyal Vardi
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipesEyal Vardi
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2Eyal Vardi
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Eyal Vardi
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModuleEyal Vardi
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xEyal Vardi
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationEyal Vardi
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And NavigationEyal Vardi
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 ArchitectureEyal Vardi
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xEyal Vardi
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 ViewsEyal Vardi
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Eyal Vardi
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0Eyal Vardi
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0Eyal Vardi
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injectionEyal Vardi
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationEyal Vardi
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScriptEyal Vardi
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 PipesEyal Vardi
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 formsEyal Vardi
 

More from Eyal Vardi (20)

Why magic
Why magicWhy magic
Why magic
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
 
Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)Angular 2 Architecture (Bucharest 26/10/2016)
Angular 2 Architecture (Bucharest 26/10/2016)
 
Angular 2 NgModule
Angular 2 NgModuleAngular 2 NgModule
Angular 2 NgModule
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.xUpgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
 
Angular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.xAngular 1.x vs. Angular 2.x
Angular 1.x vs. Angular 2.x
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
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)
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
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
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
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
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
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?
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

Asp.net web api extensibility

  • 1. ASP.NET Web API Extensibility Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com
  • 2. Expert Days 2012  © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 3. Agenda © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 4. Web API Configuration © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 5. Configuring ASP.NET Web API  Global Configuration Settings (ASP.NET Hosting)  Global Configuration Settings (Self-Hosting)  Services  Per-Controller Configuration © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 6. Global Configuration Settings (ASP.NET Hosting)  Stored in the GlobalConfiguration object, which is contains a singleton HttpConfiguration instance. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 7. HttpConfiguration Member Description DependencyResolver Enables dependency injection for controllers. Filters Action filters. Formatters Media-type formatters. Specifies whether the server should include error details, such as IncludeErrorDetailPolicy exception messages and stack traces, in HTTP response messages. Initializer A function that performs final initialization of the HttpConfiguration. MessageHandlers HTTP message handlers. ParameterBindingRules A collection of rules for binding parameters on controller actions. Properties A generic property bag. Routes The collection of routes Services The collection of services. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 8. WebApiConfig  The call to WebApiConfig.Register configures Web API. The definition for the WebApiConfig class is located in the App_Start directory. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 9. Global Configuration Settings (Self-Hosting)  If you self-host Web API, the configuration settings are stored in the HttpSelfHostConfiguration class, which derives from HttpConfiguration. var config = new HttpSelfHostConfiguration("http://localhost:8080"); // Add a route config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // Add a media-type formatter config.Formatters.Add(new MyFormatter()); © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 10. Services  The HttpConfiguration.Services collection contains a set of global services that Web API uses to perform various tasks.  Controller selection (IHttpControllerSelector)  Content negotiation (IContentNegotiator)  IActionValueBinder  IApiExplorer  IAssembliesResolver  IBodyModelValidator  IDocumentationProvider  IHttpActionInvoker  IHttpControllerTypeResolver  ITraceManager & ITraceWriter  … © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 11. Per-Controller Configuration  You can override per controller  Media-type formatters  Parameter binding rules  Services public class ControllerConfigAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor descriptor) { // Remove the JSON formatter. var jsonFormatter = settings.Formatters.JsonFormatter; settings.Formatters.Remove(jsonFormatter); // Add a custom media-type formatter. settings.Formatters.Add(new MyFormatter()); // Add a custom action selector. settings.Services.Replace(typeof(IHttpActionSelector), new MyActionSelector()); } } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 12. Routing © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 13. Routing Tables routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } constraints: new { id = @"d+" } ); Action HTTP method Relative URI Get a list of all products GET /api/products Get a product by ID GET /api/products/id Get a product by category GET /api/products?category=1 © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 14. Selecting a Controller  Controller selection is handled by the IHttpControllerSelector.SelectController method.  This method takes an HttpRequestMessage instance and returns an HttpControllerDescriptor.  The default implementation is provided by the DefaultHttpControllerSelector class. 1. Look in the route dictionary for the key "controller". 2. Take the value for this key and append the string "Controller" to get the controller type name. 3. Look for a Web API controller with this type name. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 15. Selecting a Controller  For step 3, DefaultHttpControllerSelector uses the IHttpControllerTypeResolver interface to get the list of Web API controller types.  The default implementation of IHttpControllerTypeResolver returns all public classes that:  Implement IHttpController,  Not abstract  Have a name that ends in "Controller". © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 16. Selecting a Controller © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 17. Selecting a Controller © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 18. Action Selection  Action selection done by calling the IHttpActionSelector.SelectAction method. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 19. Action Selection  The default implementation is provided by the ApiControllerActionSelector class. To select an action, it looks at the following:  The HTTP method of the request.  The "{action}" placeholder in the route template, if present.  The parameters of the actions on the controller. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 20. Action Selection Algorithm 1. Create a list of all actions on the controller that match the HTTP request method. 2. If the route dictionary has an "action" entry, remove actions whose name does not match this value. 3. Try to match action parameters to the URI, as follows: 1. For each action, get a list of the parameters that are a simple type, where the binding gets the parameter from the URI. Exclude optional parameters. 2. From this list, try to find a match for each parameter name, either in the route dictionary or in the URI query string. Matches are case insensitive and do not depend on the parameter order. 3. Select an action where every parameter in the list has a match in the URI. 4. If more that one action meets these criteria, pick the one with the most parameter matches. 4. Ignore actions with the [NonAction] attribute. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 21. Action Selection © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 22. HTTP Message Handlers © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 23. HTTP Message Handlers  HttpRequestMessage represents the HTTP request.  HttpResponseMessage represents the HTTP response.  HttpMessageHandler objects process the request and response © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 24. Client © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 25. Server  HttpServer derives from HttpMessageHandler.  The request then passes through a series of message handlers.  HttpControllerDispatcher handler uses the routing table to route the request to a Web API controller. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 26. HTTP Request in Memory var config = new HttpConfiguration(); config.Routes.MapHttpRoute( "default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); HttpServer server = new HttpServer(config); // Connect client directly to server HttpClient client = new HttpClient(server); var response = client.GetAsync("http://anything/api/products").Result; © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 27. Custom Message Handlers  Process the request message.  Call base.SendAsync to send the message to the inner handler. This step is asynchronous.  Process the response message and return it to the caller. Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken); © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 28. Custom Response Header public class CustomHeaderHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { return base.SendAsync(request, cancellationToken) .ContinueWith( (task) => { HttpResponseMessage response = task.Result; response.Headers.Add( "X-Custom-Header", "This is my custom header."); return response; } ); } } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 29. Custom Message Handlers © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 30. Formats & Model Binding © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 31. Internet Media Types  A media type, also called a MIME type.  Identifies the format of a piece of data.  Describe the format of the message body.  A media type consists of two strings, a type and a subtype. For example:  text/html  image/png  application/json HTTP/1.1 200 OK Content-Length: 95267 Content-Type: image/png Accept: text/html,application/xhtml+xml © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 32. Media Formatter  In Web API, the media type determines how Web API serializes and deserializes the HTTP message body. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 33. Custom Media Formatter © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 34. Exceptions © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 35. Exception Handling  By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.  For example, the following method returns 404, Not Found, if the id parameter is not valid. public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException( new HttpResponseMessage( HttpStatusCode.NotFound )); } return item; } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 36. Exception Filters  An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. NotImplementedException exceptions into HTTP status code 501, Not Implemented. public class NotImplExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is NotImplementedException) { context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); } } } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 37. Exception Filters © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

Editor's Notes

  1. http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api
  2. The IControllerConfiguration.Initialize method takes two parameters:An HttpControllerSettings objectAn HttpControllerDescriptor objectThe HttpControllerDescriptor contains a description of the controller, which you can examine for informational purposes (say, to distinguish between two controllers).Use the HttpControllerSettings object to configure the controller. This object contains the subset of configuration parameters that you can override on a per-controller basis. The previous example modified the formatter collection and replaced the IHttpActionSelector service. Any settings that you don&apos;t change will default to the globalHttpConfiguration object.