building services for any client with asp.net web api
Post on 31-Dec-2015
45 Views
Preview:
DESCRIPTION
TRANSCRIPT
Building services for any client with ASP.NET Web APIDaniel RothSenior Program Manager3-036
How to reach more clients?
Browsers Devices Phones Tablets
? ? ? ?
App
How to make it scale?
Browsers Devices Phones Tablets
App
? ? ? ?
Leverage the web – build Web APIs
Browsers Devices Phones Tablets
Web APIApp
What is a Web API
An HTTP service
Designed for broad reach
Uses HTTP as an application protocol, not a transport protocol
A framework for creating HTTP services that can reach a broad range of clients including browsers and mobile devices
ASP.NET Web API
Microsoft Office 2013Unified communications Web API Powering Lync Web App 2013 and Lync 2013 for Windows Phone 8
Model
Lync Server 2013
REST API
Media Manager(Media State)
UI
Lync Web App
Lync for Windows
Phone
Lync for iPhone
Lync for iPad
Lync forAndroid
OutlookWeb App
JavaScript C#/XAML Objective C Java JavaScript
JavaScript C++/C C#
Language independentModifiable
Event-DrivenMobile-optimized (battery longevity, etc.)
Web friendly (JSON & XML)
Implements the Lync signaling endpoint business logic
Shields Apps from protocol chattiness.
Keeps up with the full state to deal with client disconnection and aggregates notifications. Client App can sync the information it needs
at its own pace.
Abstracts protocol complexity and provides access to all communication
& collaboration workloads
API
WEB
ROLE
APP SRT
P
UI
ASP.NET WEB API
MODEL
UCWA
Unified Communications Web API (UCWA)
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
ASP.NET Web API
Getting started with ASP.NET Web APIIncluded with ASP.NET MVC 4 and Visual Studio 2012Available as stand-alone NuGet packagesSupported on .NET 4 and laterDocumentation 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
Your first Web API
Creating Web APIsDefine your routes (or just use the default one)
Create a new class that derives from APIControllerName your class {controller} + ControllerImplement your actions
routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
Web API dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
Web API dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
Implementing Web API actionsWeb API actions map to HTTP methodsPrefix your action name with the desired HTTP methodEx GetCustomer, PostComment, DeleteOrder, etc.
Use [HttpGet/Post/Put/Delete] if you prefer a different nameOverload 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 dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
Web API dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
Action parametersSimple parameter types are taken from the URIRoute data, query parameters
Complex parameter types come from the body (only one)Configured MediaTypeFormatters (formatters) are used to deserialize the request body based on the content typeJSON, XML, and form–url–encoded supported by default
Override using [FromUrl], [FromBody], [ModelBinder], custom parameter bindingYou can always work with HttpRequestMessage directly
Parameter validationValidation is run on the bound parametersSpecify validation rules using DataAnnotations or custom validation logicValidation errors are accumulated in the ModelStateCheck ModelState.IsValidSend back validation errors to client using Request.CreateErrorResponse(ModelState)
Web API dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
Web API dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
Web API dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
Response formatting and content negotiationReturned object is serialized in the response body using configured formattersRequest indicates preferred format using the accept headerServer selects a format for the response based on the request, action return type, configured formattersYou can always just return HttpResponseMessage directly
Scaffolding an entity framework code-first based Web API
Web API dispatcherInvoke action
Action filters
Parameter binding
Select action Exception filters
Route to controller Formatting
HttpRequestMessage
HttpResponseMessage
Authorization filters
FiltersUsed to handle cross cutting concernsAction filters run before and after invoking an actionAuthorization filters run before model binding and are specifically for authorizing the userException 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 ODataQuerySimply return IQueryable to enable OData query supportAdd an ODataQueryOptions parameter to manage the query yourself
PagingUse [Queryable(ResultLimit=10)] to limit the number of resultsAdd the new ODataMediaTypeFormatter to enable next links using the OData format
OData query and paging
ASP.NET Web API ODataFeaturesCRUD operationsQueryAtom and JSON formatsActionsModel builderService Document, $metadataInheritanceCollection properties
Coming post DecSelect, expandContainmentFunctionsChange setsNamed streamsOpen typesEtagsRecursive routing
Non-SQL data sources
Support as much query as you want
Lots of custom business logic
When to use ASP.NET Web API OData
WCF Data Services ASP.NET Web API OData
Architecture Interfaces Components
Server? Client? Server and Client Server only
Maturity Released Preview
OData coverage Full Partial, more coming
Flexibility Low High
Key requirements IQueryable -
Custom business logic Medium Easy
Formats OData only Any format
Untyped Yes No
HTTP request/response handling
Http Client
HttpClient
Handler
Host Http
Dispatcher
Http Serve
r
Message handlers Message handlers
Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
Message handlers:
Flexible hosting
Supporting multiple clients
Web API
Single Page App
Single Page Application (SPA) with ASP.NET Web API
Supporting multiple clients
Web API
Single Page App
Windows Store App
Windows Phone App
Windows Store and Windows Phone clients
SummaryASP.NET Web API is a framework for building HTTP
services that can reach any clientIt’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
http://www.asp.net/web-api
http://aspnetwebstack.codeplex.com
Resources
Please submit session evals on the Build Windows 8 App or at http://aka.ms/BuildSessions
• Follow us on Twitter @WindowsAzure
• Get Started: www.windowsazure.com/build
Resources
Please submit session evals on the Build Windows 8 App or at http://aka.ms/BuildSessions
© 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.
top related