Working with HTTP  Eyal Vardi  CEO E4D Solutions LTD  Microsoft MVP Visual C#  blog: www.eVardi.com
Expert Days 2012                                                                                 © 2010 E4D LTD. All righ...
Agenda           HTTP Message Handlers           Self Hosting           Sending HTML Form Data                  Form-u...
HTTP Message Handlers           ASP.NET Web API has a pipeline for            processing HTTP messages on both the client...
.NET Client           .Net application can use the HttpClient class            to send HTTP requests.           HttpClie...
HttpClientHandler Class           HttpClient by default uses the HttpClientHandler            class.                  Th...
Custom Message Handler for   HttpClient                                      CMH                                          ...
.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 t...
© 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     ...
Custom Response Header      public class CustomHeaderHandler : DelegatingHandler      {          protected override Task<H...
Adding CMH in Server Side             On the server side, add custom message              handlers to the MessageHandlers...
Adding CMH in Client Side           Pass the outer message handler in the            HttpClient constructor.           T...
HTTP Request in Memory           Because HttpServer is a message handler,            you can plug it directly into the Ht...
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 D...
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:       ...
<h1>Complex Type</h1><form id="form1" method="post" action="api/updates/complex"    enctype="application/x-www-form-urlenc...
Sending Form Data via AJAX    <script type="text/javascript">        $("#form1").submit(function () {            var jqxhr...
File Upload and Multipart MIME           When a form contains a file input control, the            enctype attribute shou...
File Upload© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
Upcoming SlideShare
Loading in...5
×

Working with http

1,095

Published on

ASP.NET Web API's working with HTTP

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
1,095
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Working with http"

  1. 1. Working with HTTP Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com
  2. 2. Expert Days 2012 © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  3. 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. 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. 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. 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. 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. 8. .NET Client© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  9. 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. 10. © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  11. 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. 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. 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. 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. 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. 16. Custom Message Handlers© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  17. 17. Self Host Config© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  18. 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. 19. Sending HTML Form Data© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
  20. 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. 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. 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. 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. 24. File Upload© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

×