400 likes | 524 Views
Building services for any client with ASP.NET Web API. Daniel Roth Senior Program Manager 3-036. How to reach more clients?. App. Devices. Browsers. Phones. ?. ?. ?. ?. Tablets. How to make it scale?. App. Devices. Browsers. Phones. ?. ?. ?. ?. Tablets.
E N D
Building services for any client with ASP.NET Web API Daniel Roth Senior Program Manager 3-036
How to reach more clients? App Devices Browsers Phones ? ? ? ? Tablets
How to make it scale? App Devices Browsers Phones ? ? ? ? Tablets
Leverage the web – build Web APIs App Web API Devices Browsers Phones Tablets
What is a Web API An HTTP service Designed for broad reach Uses HTTP as an application protocol, not a transport protocol
ASP.NET Web API • A framework for creating HTTP services that can reach a broad range of clients including browsers and mobile devices
Microsoft Office 2013Unified communications Web API Powering Lync Web App 2013 and Lync 2013 for Windows Phone 8
Unified Communications Web API (UCWA) UI A P P U I Model Media Manager (Media State) M O D E L SRTP A P I REST API Lync Server 2013 UCWA ASP.NET WEB API WE B RO L E
ASP.NET Web API • First-class modern HTTP • programming model • Easily map resources to URIs and implement the uniform interface of HTTP • Rich support for formats and HTTP content negotiation • Enable hypermedia and link generation • Separate out cross cutting concerns • Flexible hosting • Light-weight, testable, scales
Getting started with ASP.NET Web API • Included with ASP.NET MVC 4 and Visual Studio 2012 • Available as stand-alone NuGet packages • Supported on .NET 4 and later • Documentation on http://www.asp.net/web-api • Install the ASP.NET Fall 2012 Update preview (http://www.asp.net/vnext) to get the latest features
Creating Web APIs • Define your routes (or just use the default one) • Create a new class that derives from APIController • Name your class {controller} + Controller • Implement your actions routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional});
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Implementing Web API actions • Web API actions map to HTTP methods • Prefix your action name with the desired HTTP method • Ex GetCustomer, PostComment, DeleteOrder, etc. • Use [HttpGet/Post/Put/Delete] if you prefer a different name • Overload actions based on the presence of data in the URI • Note: Action selection can also be done using the {action} route variable just like MVC IEnumerable<Customer> Get() {…} Customer Get(int id) {…}
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Action parameters • Simple parameter types are taken from the URI • Route data, query parameters • Complex parameter types come from the body (only one) • Configured MediaTypeFormatters (formatters) are used to deserializethe request body based on the content type • JSON, XML, and form–url–encoded supported by default • Override using [FromUrl], [FromBody], [ModelBinder], custom parameter binding • You can always work with HttpRequestMessage directly
Parameter validation • Validation is run on the bound parameters • Specify validation rules using DataAnnotations or custom validation logic • Validation errors are accumulated in the ModelState • Check ModelState.IsValid • Send back validation errors to client using Request.CreateErrorResponse(ModelState)
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Response formatting and content negotiation • Returned object is serialized in the response body using configured formatters • Request indicates preferred format using the accept header • Server selects a format for the response based on the request, action return type, configured formatters • You can always just return HttpResponseMessage directly
Web API dispatcher Invoke action Action filters Parameter binding Authorization filters Select action Exception filters Route to controller Formatting HttpRequestMessage HttpResponseMessage
Filters • Used to handle cross cutting concerns • 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 • Configured globally, per controller, or per action as an attribute (ex [Authorize])
ASP.NET Web API OData • Query • Simply return IQueryable to enable OData query support • Add an ODataQueryOptions parameter to manage the query yourself • Paging • Use [Queryable(ResultLimit=10)] to limit the number of results • Add the new ODataMediaTypeFormatter to enable next links using the OData format
ASP.NET Web API OData Coming post Dec Select, expand Containment Functions Change sets Named streams Open types Etags Recursive routing • Features • CRUD operations • Query • Atom and JSON formats • Actions • Model builder • Service Document, $metadata • Inheritance • Collection properties
When to use ASP.NET Web API OData • Non-SQL data sources • Support as much query as you want • Lots of custom business logic
HTTP request/response handling Message handlers Message handlers Host Http Server Http Dispatcher HttpClient Handler Http Client • Message handlers: • Task<HttpResponseMessage> SendAsync( • HttpRequestMessagerequest, • CancellationTokencancellationToken)
Supporting multiple clients Web API Single Page App
Supporting multiple clients Web API Windows Phone App Windows Store App Single Page App
Summary • ASP.NET Web API is a framework for building HTTP services that can reach any client • It’s great for building Azure hosted back ends for Windows Store and Windows Phone apps • Try out the new Single Page Application, OData, Help Page, and Tracing support in the ASP.NET Fall 2012 Update preview
Resources • http://www.asp.net/web-api • http://aspnetwebstack.codeplex.com Please submit session evals on the Build Windows 8 App or at http://aka.ms/BuildSessions
Resources • Follow us on Twitter @WindowsAzure • Get Started: www.windowsazure.com/build Please submit session evals on the Build Windows 8 App or at http://aka.ms/BuildSessions