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

Recommended

PDF
Asp.net mvc internals & extensibility
Eyal Vardi
 
PPTX
Asp.Net Mvc Internals &amp; Extensibility
Eyal Vardi
 
PPTX
Prism Navigation
Eyal Vardi
 
PPTX
Models
Eyal Vardi
 
PPTX
Single Page JavaScript WebApps... A Gradle Story
Kon Soulianidis
 
PPTX
Asp.net mvc filters
Eyal Vardi
 
PPTX
Web api routing
Eyal Vardi
 
PDF
Bt0083 server side programing
Techglyphs
 
PDF
Document_format_for_OData_In_A_Nutshell.pdf
davidjpeace
 
PDF
Creating Great REST and gRPC API Experiences (in Swift)
Tim Burks
 
PPTX
Joget Workflow v6 Training Slides - 18 - Integrating with External System
Joget Workflow
 
PPTX
TechEvent Eclipse Microprofile
Trivadis
 
PDF
Protocol
m_bahba
 
PPT
Wcf data services
Eyal Vardi
 
PPT
Spring training
TechFerry
 
PPTX
Ektron CMS400 8.02
Alpesh Patel
 
PPT
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
PPTX
There is time for rest
SoftServe
 
PPTX
Overview of MVC Framework - by software outsourcing company india
Jignesh Aakoliya
 
PDF
MuleSoft London Community February 2020 - MuleSoft and OData
Pace Integration
 
PPTX
ASP.NET Mvc 4 web api
Tiago Knoch
 
PPTX
Odata introduction
Ahmad Dwedar
 
PDF
Webservices in SalesForce (part 1)
Mindfire Solutions
 
PPT
An Introduction To Java Web Technology
vikram singh
 
PPT
Web Tech Java Servlet Update1
vikram singh
 
PPTX
Mike Taulty OData (NxtGen User Group UK)
ukdpe
 
PPS
RIA and Ajax
Schubert Gomes
 
PDF
10 Ace 2010 Aras Federation Workshop
Prodeos
 
PPTX
Why magic
Eyal Vardi
 
PPTX
Smart Contract
Eyal Vardi
 

More Related Content

Similar to Asp.net web api extensibility (20)

PDF
Document_format_for_OData_In_A_Nutshell.pdf
davidjpeace
 
PDF
Creating Great REST and gRPC API Experiences (in Swift)
Tim Burks
 
PPTX
Joget Workflow v6 Training Slides - 18 - Integrating with External System
Joget Workflow
 
PPTX
TechEvent Eclipse Microprofile
Trivadis
 
PDF
Protocol
m_bahba
 
PPT
Wcf data services
Eyal Vardi
 
PPT
Spring training
TechFerry
 
PPTX
Ektron CMS400 8.02
Alpesh Patel
 
PPT
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
PPTX
There is time for rest
SoftServe
 
PPTX
Overview of MVC Framework - by software outsourcing company india
Jignesh Aakoliya
 
PDF
MuleSoft London Community February 2020 - MuleSoft and OData
Pace Integration
 
PPTX
ASP.NET Mvc 4 web api
Tiago Knoch
 
PPTX
Odata introduction
Ahmad Dwedar
 
PDF
Webservices in SalesForce (part 1)
Mindfire Solutions
 
PPT
An Introduction To Java Web Technology
vikram singh
 
PPT
Web Tech Java Servlet Update1
vikram singh
 
PPTX
Mike Taulty OData (NxtGen User Group UK)
ukdpe
 
PPS
RIA and Ajax
Schubert Gomes
 
PDF
10 Ace 2010 Aras Federation Workshop
Prodeos
 
Document_format_for_OData_In_A_Nutshell.pdf
davidjpeace
 
Creating Great REST and gRPC API Experiences (in Swift)
Tim Burks
 
Joget Workflow v6 Training Slides - 18 - Integrating with External System
Joget Workflow
 
TechEvent Eclipse Microprofile
Trivadis
 
Protocol
m_bahba
 
Wcf data services
Eyal Vardi
 
Spring training
TechFerry
 
Ektron CMS400 8.02
Alpesh Patel
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
There is time for rest
SoftServe
 
Overview of MVC Framework - by software outsourcing company india
Jignesh Aakoliya
 
MuleSoft London Community February 2020 - MuleSoft and OData
Pace Integration
 
ASP.NET Mvc 4 web api
Tiago Knoch
 
Odata introduction
Ahmad Dwedar
 
Webservices in SalesForce (part 1)
Mindfire Solutions
 
An Introduction To Java Web Technology
vikram singh
 
Web Tech Java Servlet Update1
vikram singh
 
Mike Taulty OData (NxtGen User Group UK)
ukdpe
 
RIA and Ajax
Schubert Gomes
 
10 Ace 2010 Aras Federation Workshop
Prodeos
 

More from Eyal Vardi (20)

PPTX
Why magic
Eyal Vardi
 
PPTX
Smart Contract
Eyal Vardi
 
PDF
Rachel's grandmother's recipes
Eyal Vardi
 
PPTX
Performance Optimization In Angular 2
Eyal Vardi
 
PPTX
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi
 
PPTX
Angular 2 NgModule
Eyal Vardi
 
PPTX
Upgrading from Angular 1.x to Angular 2.x
Eyal Vardi
 
PPTX
Angular 2 - Ahead of-time Compilation
Eyal Vardi
 
PPTX
Routing And Navigation
Eyal Vardi
 
PPTX
Angular 2 Architecture
Eyal Vardi
 
PPTX
Angular 1.x vs. Angular 2.x
Eyal Vardi
 
PPTX
Angular 2.0 Views
Eyal Vardi
 
PPTX
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
PPTX
Template syntax in Angular 2.0
Eyal Vardi
 
PPTX
Http Communication in Angular 2.0
Eyal Vardi
 
PPTX
Angular 2.0 Dependency injection
Eyal Vardi
 
PPTX
Angular 2.0 Routing and Navigation
Eyal Vardi
 
PPTX
Async & Parallel in JavaScript
Eyal Vardi
 
PPTX
Angular 2.0 Pipes
Eyal Vardi
 
PPTX
Angular 2.0 forms
Eyal Vardi
 
Why magic
Eyal Vardi
 
Smart Contract
Eyal Vardi
 
Rachel's grandmother's recipes
Eyal Vardi
 
Performance Optimization In Angular 2
Eyal Vardi
 
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi
 
Angular 2 NgModule
Eyal Vardi
 
Upgrading from Angular 1.x to Angular 2.x
Eyal Vardi
 
Angular 2 - Ahead of-time Compilation
Eyal Vardi
 
Routing And Navigation
Eyal Vardi
 
Angular 2 Architecture
Eyal Vardi
 
Angular 1.x vs. Angular 2.x
Eyal Vardi
 
Angular 2.0 Views
Eyal Vardi
 
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
Template syntax in Angular 2.0
Eyal Vardi
 
Http Communication in Angular 2.0
Eyal Vardi
 
Angular 2.0 Dependency injection
Eyal Vardi
 
Angular 2.0 Routing and Navigation
Eyal Vardi
 
Async & Parallel in JavaScript
Eyal Vardi
 
Angular 2.0 Pipes
Eyal Vardi
 
Angular 2.0 forms
Eyal Vardi
 
Ad

Recently uploaded (20)

PDF
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
PDF
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
PPTX
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
 
PDF
The Growing Value and Application of FME & GenAI
Safe Software
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PDF
Python Conference Singapore - 19 Jun 2025
ninefyi
 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PDF
Kubernetes - Architecture & Components.pdf
geethak285
 
PDF
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
PDF
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
PDF
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
DOCX
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
PPTX
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
PDF
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
reInforce 2025 Lightning Talk - Scott Francis.pptx
ScottFrancis51
 
The Growing Value and Application of FME & GenAI
Safe Software
 
Practical Applications of AI in Local Government
OnBoard
 
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
Kubernetes - Architecture & Components.pdf
geethak285
 
Optimizing the trajectory of a wheel loader working in short loading cycles
Reno Filla
 
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
5 Things to Consider When Deploying AI in Your Enterprise
Safe Software
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
𝙳𝚘𝚠𝚗𝚕𝚘𝚊𝚍—Wondershare Filmora Crack 14.0.7 + Key Download 2025
sebastian aliya
 
“Scaling i.MX Applications Processors’ Native Edge AI with Discrete AI Accele...
Edge AI and Vision Alliance
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
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.