SlideShare a Scribd company logo
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
Ad

More Related Content

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
davidjpeace
 
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 System
Joget Workflow
 
TechEvent Eclipse Microprofile
TechEvent Eclipse MicroprofileTechEvent Eclipse Microprofile
TechEvent Eclipse Microprofile
Trivadis
 
Protocol
ProtocolProtocol
Protocol
m_bahba
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
Eyal Vardi
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Ektron CMS400 8.02
Ektron CMS400 8.02Ektron CMS400 8.02
Ektron CMS400 8.02
Alpesh Patel
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
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 india
Jignesh 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 OData
Pace Integration
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Odata introduction
Odata introductionOdata introduction
Odata introduction
Ahmad 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 Technology
vikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram 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
 
RIA and Ajax
RIA and AjaxRIA and Ajax
RIA and Ajax
Schubert Gomes
 
10 Ace 2010 Aras Federation Workshop
10 Ace 2010 Aras Federation Workshop10 Ace 2010 Aras Federation Workshop
10 Ace 2010 Aras Federation Workshop
Prodeos
 
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
davidjpeace
 
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 System
Joget Workflow
 
TechEvent Eclipse Microprofile
TechEvent Eclipse MicroprofileTechEvent Eclipse Microprofile
TechEvent Eclipse Microprofile
Trivadis
 
Protocol
ProtocolProtocol
Protocol
m_bahba
 
Wcf data services
Wcf data servicesWcf data services
Wcf data services
Eyal Vardi
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Ektron CMS400 8.02
Ektron CMS400 8.02Ektron CMS400 8.02
Ektron CMS400 8.02
Alpesh Patel
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
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 india
Jignesh 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 OData
Pace Integration
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Odata introduction
Odata introductionOdata introduction
Odata introduction
Ahmad 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 Technology
vikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram 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 Workshop
Prodeos
 

More from Eyal Vardi (20)

Why magic
Why magicWhy magic
Why magic
Eyal Vardi
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
Eyal Vardi
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
Eyal Vardi
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
Eyal 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 NgModule
Eyal 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.x
Eyal Vardi
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
Eyal Vardi
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
Eyal Vardi
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
Eyal 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.x
Eyal Vardi
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
Eyal 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.0
Eyal Vardi
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
Eyal Vardi
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
Eyal Vardi
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
Eyal Vardi
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
Eyal Vardi
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
Eyal Vardi
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
Eyal Vardi
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi
 
Smart Contract
Smart ContractSmart Contract
Smart Contract
Eyal Vardi
 
Rachel's grandmother's recipes
Rachel's grandmother's recipesRachel's grandmother's recipes
Rachel's grandmother's recipes
Eyal Vardi
 
Performance Optimization In Angular 2
Performance Optimization In Angular 2Performance Optimization In Angular 2
Performance Optimization In Angular 2
Eyal 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 NgModule
Eyal 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.x
Eyal Vardi
 
Angular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time CompilationAngular 2 - Ahead of-time Compilation
Angular 2 - Ahead of-time Compilation
Eyal Vardi
 
Routing And Navigation
Routing And NavigationRouting And Navigation
Routing And Navigation
Eyal Vardi
 
Angular 2 Architecture
Angular 2 ArchitectureAngular 2 Architecture
Angular 2 Architecture
Eyal 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.x
Eyal Vardi
 
Angular 2.0 Views
Angular 2.0 ViewsAngular 2.0 Views
Angular 2.0 Views
Eyal 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.0
Eyal Vardi
 
Template syntax in Angular 2.0
Template syntax in Angular 2.0Template syntax in Angular 2.0
Template syntax in Angular 2.0
Eyal Vardi
 
Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
Eyal Vardi
 
Angular 2.0 Dependency injection
Angular 2.0 Dependency injectionAngular 2.0 Dependency injection
Angular 2.0 Dependency injection
Eyal Vardi
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
Eyal Vardi
 
Async & Parallel in JavaScript
Async & Parallel in JavaScriptAsync & Parallel in JavaScript
Async & Parallel in JavaScript
Eyal Vardi
 
Angular 2.0 Pipes
Angular 2.0 PipesAngular 2.0 Pipes
Angular 2.0 Pipes
Eyal Vardi
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi
 
Ad

Recently uploaded (20)

ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Ad

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: [email protected]
  • 3. Agenda © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 4. Web API Configuration © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 12. Routing © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 16. Selecting a Controller © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 17. Selecting a Controller © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 18. Action Selection  Action selection done by calling the IHttpActionSelector.SelectAction method. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 21. Action Selection © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 22. HTTP Message Handlers © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 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: [email protected]
  • 24. Client © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 29. Custom Message Handlers © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 30. Formats & Model Binding © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 33. Custom Media Formatter © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 34. Exceptions © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]
  • 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: [email protected]
  • 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: [email protected]
  • 37. Exception Filters © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: [email protected]

Editor's Notes

  • #8: http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api
  • #12: 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.