SlideShare uma empresa Scribd logo
1 de 24
Working with HTTP


  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
           HTTP Message Handlers

           Self Hosting

           Sending HTML Form Data
                  Form-urlencoded Data

                  File Upload and Multipart MIME




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HTTP Message Handlers
           ASP.NET Web API has a pipeline for
            processing HTTP messages on both the client
            and server.
                  HttpRequestMessage

                  HttpResponseMessage

                  HttpMessageHandler
                   objects process the request and response




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
.NET Client
           .Net application can use the HttpClient class
            to send HTTP requests.
           HttpClient sends the request to a message
            handler. The message handler returns an
            HttpResponseMessage.
                                                                                 Abstract




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HttpClientHandler Class
           HttpClient by default uses the HttpClientHandler
            class.
                  This class is a message handler that converts the
                   HttpRequestMessage into an HTTP request, sends the HTTP
                   request over the network, and converts the HTTP response
                   into an HttpResponseMessage.




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

                                      CMH

                                             CMH

                                                    CMH




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




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Server Message Handlers
           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.                             CMH

                                                            CMH




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
© 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
Adding CMH in Server Side
             On the server side, add custom message
              handlers to the MessageHandlers collection
              on the HttpConfiguration object.
             Message handlers are called in the reverse
              order of the MessageHandlers collection.
     public static class WebApiConfig
     {
        public static void Register(HttpConfiguration config)                    Last
        {
            config.MessageHandlers.Add(new MethodOverrideHandler());
            config.MessageHandlers.Add(new CustomHeaderHandler());
            config.MessageHandlers.Add(new ApiKeyHandler("secret"));

               // Other code not shown...                                        First
          }
     }

© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Adding CMH in Client Side
           Pass the outer message handler in the
            HttpClient constructor.
           To chain more than one message handler, you
            must set the InnerHandler property of each
            message handler in the chain.

                     var handler = new CustomHeaderHandler()
                     {
                         InnerHandler = new HttpClientHandler()
                     };

                     HttpClient client = new HttpClient(handler);


© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
HTTP Request in Memory
           Because HttpServer is a message handler,
            you can plug it directly into the HttpClient
            class.

        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

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




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Self Host
   var config = new HttpSelfHostConfiguration("http://localhost:8080");

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

   using (HttpSelfHostServer server = new HttpSelfHostServer(config))
   {
      server.OpenAsync().Wait();
      Console.ReadLine();
   }




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




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Enctype Attribute in Form Tag
           The enctype attribute specifies the format of
            the request body:

         enctype                       Description

         application/x-www- Form data is encoded as name/value pairs, similar to a
         form-urlencoded    URI query string. This is the default format for POST.


                                       Form data is encoded as a multipart MIME message. Use
         multipart/form-data
                                       this format if you are uploading a file to the server.




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
<h1>Complex Type</h1>
<form id="form1" method="post" action="api/updates/complex"
    enctype="application/x-www-form-urlencoded">
    <div>
        <label for="status">Status</label>
    </div>
    <div>
        <input name="status" type="text" />
    </div>
    <div>
        <label for="date">Date</label>
    </div>
    <div>
        <input name="date" type="text" />
    </div>
    <div>
        <input type="submit" value="Submit" />
      POST http://localhost:38899/api/updates/complex HTTP/1.1
    </div>
      Accept: text/html, application/xhtml+xml, */*
</form>
      User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64;
         Trident/5.0)
         Content-Type: application/x-www-form-urlencoded
         Content-Length: 47

         status=Shopping+at+the+mall.&date=6%2F15%2F2012




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Sending Form Data via AJAX
    <script type="text/javascript">
        $("#form1").submit(function () {
            var jqxhr = $.post('api/updates/complex', $('#form1').serialize())
                .success(function () {
                    var loc = jqxhr.getResponseHeader('Location');
                    var a = $('<a/>', { href: loc, text: loc });
                    $('#message').html(a);
                })
                .error(function () {
                    $('#message').html("Error posting the update.");
                });
            return false;
        });
    </script>




© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
File Upload and Multipart MIME
           When a form contains a file input control, the
            enctype attribute should always be
            "multipart/form-data".
     <form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
        <div>
             <label for="caption">Image Caption</label>
             <input name="caption" type="text" />
        </div>
        <div>
             <label for="image1">Image File</label>
             <input name="image1" type="file" />
        </div>
        <div>
             <input type="submit" value="Submit" />
        </div>
     </form>




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

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

Mais conteúdo relacionado

Mais de 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
 
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
 
Modules and injector
Modules and injectorModules and injector
Modules and injectorEyal Vardi
 

Mais de 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
 
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
 
Modules and injector
Modules and injectorModules and injector
Modules and injector
 

Último

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Working with http

  • 1. Working with HTTP 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  HTTP Message Handlers  Self Hosting  Sending HTML Form Data  Form-urlencoded Data  File Upload and Multipart MIME © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 4. HTTP Message Handlers  ASP.NET Web API has a pipeline for processing HTTP messages on both the client and server.  HttpRequestMessage  HttpResponseMessage  HttpMessageHandler objects process the request and response © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 5. .NET Client  .Net application can use the HttpClient class to send HTTP requests.  HttpClient sends the request to a message handler. The message handler returns an HttpResponseMessage. Abstract © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 6. HttpClientHandler Class  HttpClient by default uses the HttpClientHandler class.  This class is a message handler that converts the HttpRequestMessage into an HTTP request, sends the HTTP request over the network, and converts the HTTP response into an HttpResponseMessage. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 7. Custom Message Handler for HttpClient CMH CMH CMH © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 8. .NET Client © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 9. Server Message Handlers  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. CMH CMH © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 10. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 11. 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
  • 12. 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
  • 13. Adding CMH in Server Side  On the server side, add custom message handlers to the MessageHandlers collection on the HttpConfiguration object.  Message handlers are called in the reverse order of the MessageHandlers collection. public static class WebApiConfig { public static void Register(HttpConfiguration config) Last { config.MessageHandlers.Add(new MethodOverrideHandler()); config.MessageHandlers.Add(new CustomHeaderHandler()); config.MessageHandlers.Add(new ApiKeyHandler("secret")); // Other code not shown... First } } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 14. Adding CMH in Client Side  Pass the outer message handler in the HttpClient constructor.  To chain more than one message handler, you must set the InnerHandler property of each message handler in the chain. var handler = new CustomHeaderHandler() { InnerHandler = new HttpClientHandler() }; HttpClient client = new HttpClient(handler); © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 15. HTTP Request in Memory  Because HttpServer is a message handler, you can plug it directly into the HttpClient class. 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
  • 16. Custom Message Handlers © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 17. Self Host Config © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 18. Self Host var config = new HttpSelfHostConfiguration("http://localhost:8080"); config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); using (HttpSelfHostServer server = new HttpSelfHostServer(config)) { server.OpenAsync().Wait(); Console.ReadLine(); } © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 19. Sending HTML Form Data © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 20. Enctype Attribute in Form Tag  The enctype attribute specifies the format of the request body: enctype Description application/x-www- Form data is encoded as name/value pairs, similar to a form-urlencoded URI query string. This is the default format for POST. Form data is encoded as a multipart MIME message. Use multipart/form-data this format if you are uploading a file to the server. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 21. <h1>Complex Type</h1> <form id="form1" method="post" action="api/updates/complex" enctype="application/x-www-form-urlencoded"> <div> <label for="status">Status</label> </div> <div> <input name="status" type="text" /> </div> <div> <label for="date">Date</label> </div> <div> <input name="date" type="text" /> </div> <div> <input type="submit" value="Submit" /> POST http://localhost:38899/api/updates/complex HTTP/1.1 </div> Accept: text/html, application/xhtml+xml, */* </form> User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Content-Type: application/x-www-form-urlencoded Content-Length: 47 status=Shopping+at+the+mall.&date=6%2F15%2F2012 © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 22. Sending Form Data via AJAX <script type="text/javascript"> $("#form1").submit(function () { var jqxhr = $.post('api/updates/complex', $('#form1').serialize()) .success(function () { var loc = jqxhr.getResponseHeader('Location'); var a = $('<a/>', { href: loc, text: loc }); $('#message').html(a); }) .error(function () { $('#message').html("Error posting the update."); }); return false; }); </script> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 23. File Upload and Multipart MIME  When a form contains a file input control, the enctype attribute should always be "multipart/form-data". <form name="form1" method="post" enctype="multipart/form-data" action="api/upload"> <div> <label for="caption">Image Caption</label> <input name="caption" type="text" /> </div> <div> <label for="image1">Image File</label> <input name="image1" type="file" /> </div> <div> <input type="submit" value="Submit" /> </div> </form> © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  • 24. File Upload © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il