1 / 46

Building HTTP Services with ASP.NET Web API

DEV309. Building HTTP Services with ASP.NET Web API. Sayed Ibrahim Hashimi Program Manager Microsoft Corporation. Contact info. @SayedIHashimi SayedHa@microsoft.com http://sedodream.com/. What is a Web API?. An HTTP service. Designed for broad reach.

faris
Télécharger la présentation

Building HTTP Services with ASP.NET Web API

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. DEV309 Building HTTP Services with ASP.NET Web API Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  2. Contact info • @SayedIHashimi • SayedHa@microsoft.com • http://sedodream.com/

  3. What is a Web API? An HTTP service Designed for broad reach Uses HTTP as an application protocol, not a transport protocol

  4. Why build Web APIs?

  5. Reach More Clients

  6. Scale with the Cloud

  7. Embrace HTTP • GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1 • Host: www.explainth.at • User-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11 • Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 • Accept-Language: en-gb,en;q=0.5 • Accept-Encoding: gzip,deflate • Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 • Keep-Alive: 300 • Connection: keep-alive • Referer: http://www.explainth.at/en/misc/httpreq.shtml

  8. demo Contact Manager browser and mobile app Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  9. Web API framework requirements • Need a first class HTTP programming model • Easily map resources to URIs and implement the uniform interface • Rich support for formats and HTTP content negotiation • Separate out cross cutting concerns • Light weight, testable, scales

  10. So you want to create a Web API . . . ? WCF Web HTTP WCF REST Starter Kit WCF Web API ASP.NET MVC

  11. So you want to create a Web API . . . + WCF Web HTTP WCF REST Starter Kit WCF Web API ASP.NET MVC

  12. So you want to create a Web API . . . ASP.NET Web API

  13. ASP.NET Web API Features From ASP.NET MVC From WCF Web API Modern HTTP programming model HttpClient Task-based async Formatting, content negotiation Server-side query composition Create custom help pages Self-host Tracing • ASP.NET Routing • Model binding • Validation • Filters • Link generation • Testability • IoCintegration • VS template • Scaffolding

  14. http://www.asp.net/web-api

  15. We are open source!http://aspnetwebstack.codeplex.com

  16. demo Your First Web API Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  17. To implement a Web API . . . Derive from ApiController Implement your actions • Actions map to HTTP methods • Prefix method name with desired HTTP method – PostComment • Use [HttpGet/Post/Put/Delete] if you prefer a different name

  18. Routing Maps a URI space to your ApiControllers • Ex. api/{controller}/{id} • {controller} + “Controller” = ApiController type name Can be tailored using default values and route constraints

  19. Default Web API route • routes.MapHttpRoute( • name: "DefaultApi", • routeTemplate: "api/{controller}/{id}", • defaults: new { id = RouteParameter.Optional } • );

  20. Action parameters Simple types are taken from the URI • Route data, query parameters Complex types come from the body • Configured MediaTypeFormatters are used to deserialize the request body based on the content type • JSON, XML, and form-url-encoded supported out of the box Override using [FromUrl], [FromBody], [ModelBinder], custom parameter binding

  21. Validation • Validation is run on the data from every request • Validation errors are accumulated in the ModelState • Check ModelState.IsValid • Uses DataAnnotations or custom validation logic

  22. Content Negotiation Response format is determined based on HTTP content negotiation Accept header in request expresses desired format(s) Server selects a format for the response based on the: • Request • Action return type • Configured MediaTypeFormatters JSON and XML supported out of the box

  23. Content Negotiation • // Get the IContentNegotiator • IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator(); • // Run content negotiation to select a formatter • MediaTypeHeaderValuemediaType; • MediaTypeFormatter formatter = negotiator.Negotiate( • typeof(Contact), Request, Configuration.Formatters, out mediaType); • // Create a response message with an object content using the selected formatter • HttpResponseMessage response = new HttpResponseMessage() • { • Content = new ObjectContent<Contact>(contact, formatter), • RequestMessage= Request • };

  24. Content Negotiation • HttpResponseMessage response = • Request.CreateResponse<Contact>(HttpStatusCode.Created, contact);

  25. demo Scaffolding an EF-based web API Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  26. Filters Filters are used to handle cross cutting concerns Filter types: • Action filters run before and after invoking an action • Authorization filters run before model binding and are specifically for authorizing the user • Exception filters handle generating responses for error cases in a centralized way Filters can be configured globally, per controller, or per action as an attribute

  27. HTTP Dispatcher Invoke Action Action filters Model Bind Authorization filters Select action Exception filters Route to controller Formatting Request Response

  28. OData queries Support for OData URL query syntax • $top, $skip, $orderby, $filter Enable query using [Queryable] filter and returning IQueryable<T> from a method Orthogonal to format and content negotiation

  29. demo OData query support Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  30. HTTP request/response handling Message handlers Message handlers Host Http Server Http Dispatcher HttpClient Handler Http Client • Message handlers: • Task<HttpResponseMessage> SendAsync( • HttpRequestMessagerequest, • CancellationTokencancellationToken)

  31. demo URI format extensions Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  32. Web API description • Use the IApiExplorer service to get a runtime description of the Web API • Useful for building custom help pages, test clients, and tooling

  33. IApiExplorer • IApiExplorerapiExplorer = • config.Services.GetApiExplorer(); • public interface IApiExplorer • { • Collection<ApiDescription> ApiDescriptions { get; } • }

  34. demo Custom web API help page Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  35. Hosting • Two hosting options today • ASP.NET Web Application (IIS) • Self-host server option (ex. console application, Windows service, Azure Worker Role, etc.) • HttpConfiguration is the common denominator • Host in memory for end-to-end testing • Use an OWIN bridge to host on any OWIN compatible web server

  36. demo Flexible hosting Sayed Ibrahim Hashimi Program Manager Microsoft Corporation

  37. The Road Ahead • ASP.NET Web API ships with ASP.NET MVC 4 • Supported on .NET 4 • Ships in the box with Visual Studio 2012 • Release Candidate available via Web Platform Installer, NuGet, Visual Studio 2012 RC

  38. Summary • ASP.NET Web API in MVC 4 makes it easy to build HTTP services that can reach a broad set of clients • ASP.NET Web API is an ideal platform for creating RESTful services • Try out the ASP.NET MVC 4 Release Candidate • Follow our progress on CodePlex

  39. Contact info • @SayedIHashimi • SayedHa@microsoft.com • http://sedodream.com/

  40. Related Content • DEV301 ASP.NET Roadmap: One ASP.NET – Web Forms, MVC, Web API, and more DEV302 What's New in Visual Studio 2012 for Web Developers DEV303 ASP.NET Loves HTML5 DEV304 ASP.NET for Mobile and Tablet Development • DEV305 Microsoft ASP.NET and the Realtime Web

  41. DEV Track Resources • Visual Studio Home Page :: http://www.microsoft.com/visualstudio/en-us Somasegar’s Blog :: http://blogs.msdn.com/b/somasegar/ Jason Zander’s Blog :: http://blogs.msdn.com/b/jasonz/ Facebook :: http://www.facebook.com/visualstudio Twitter :: http://twitter.com/#!/visualstudio

  42. Resources Learning TechNet • Connect. Share. Discuss. • Microsoft Certification & Training Resources http://europe.msteched.com www.microsoft.com/learning • Resources for IT Professionals • Resources for Developers • http://microsoft.com/technet http://microsoft.com/msdn

  43. Evaluations Submit your evals online http://europe.msteched.com/sessions

  44. © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

More Related