46

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

Embed Size (px)

Citation preview

Building HTTP Services with ASP.NET Web API

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

DEV309

Contact info

@SayedIHashimi

[email protected]

http://sedodream.com/

What is a Web API?

An HTTP service

Designed for broad reach

Uses HTTP as an application protocol, not a transport protocol

Why build Web APIs?

Why build Web APIs?

Reach More Clients

Why build Web APIs?

Scale with the Cloud

Why build Web APIs?

Embrace HTTP

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

demo

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

Contact Manager browser and mobile app

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

So you want to create a Web API . . .

?ASP.NET MVC

WCF Web HTTPWCF REST Starter KitWCF Web API

So you want to create a Web API . . .

+ASP.NET MVC

WCF Web HTTPWCF REST Starter KitWCF Web API

So you want to create a Web API . . .

ASP.NET Web API

ASP.NET Web API Features

From ASP.NET MVC

ASP.NET RoutingModel bindingValidationFiltersLink generationTestabilityIoC integrationVS templateScaffolding

From WCF Web API

Modern HTTP programming modelHttpClientTask-based asyncFormatting, content negotiationServer-side query compositionCreate custom help pagesSelf-hostTracing

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

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

demo

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

Your First Web API

To implement a Web API . . .

Derive from ApiController

Implement your actionsActions map to HTTP methods

Prefix method name with desired HTTP method – PostComment

Use [HttpGet/Post/Put/Delete] if you prefer a different name

Routing

Maps a URI space to your ApiControllersEx. api/{controller}/{id}

{controller} + “Controller” = ApiController type name

Can be tailored using default values and route constraints

Default Web API route

routes.MapHttpRoute(

name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional });

Action parameters

Simple types are taken from the URIRoute data, query parameters

Complex types come from the bodyConfigured 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

Validation

Validation is run on the data from every requestValidation errors are accumulated in the ModelStateCheck ModelState.IsValidUses DataAnnotations or custom validation logic

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

Content Negotiation

// Get the IContentNegotiator

IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();

// Run content negotiation to select a formatter

MediaTypeHeaderValue mediaType;

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

};

Content Negotiation

HttpResponseMessage response =

Request.CreateResponse<Contact>(HttpStatusCode.Created, contact);

demo

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

Scaffolding an EF-based web API

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

HTTP DispatcherInvoke Action

Action filters

Model Bind

Select action Exception filters

Route to controller Formatting

Request Response

Authorization filters

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

demo

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

OData query support

HTTP request/response handling

Http Clien

t

HttpClient

Handler

Host Http

Dispatcher

Http Server

Message handlers Message handlers

Message handlers:Task<HttpResponseMessage> SendAsync(

HttpRequestMessage request,

CancellationToken cancellationToken)

demo

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

URI format extensions

Web API description

Use the IApiExplorer service to get a runtime description of the Web APIUseful for building custom help pages, test clients, and tooling

IApiExplorer

IApiExplorer apiExplorer =

config.Services.GetApiExplorer();

public interface IApiExplorer{Collection<ApiDescription> ApiDescriptions { get; }

}

demo

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

Custom web API help page

Hosting

Two hosting options todayASP.NET Web Application (IIS)Self-host server option (ex. console application, Windows service, Azure Worker Role, etc.)

HttpConfiguration is the common denominatorHost in memory for end-to-end testingUse an OWIN bridge to host on any OWIN compatible web server

demo

Sayed Ibrahim HashimiProgram ManagerMicrosoft Corporation

Flexible hosting

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

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

Contact info

@SayedIHashimi

[email protected]

http://sedodream.com/

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

DEV Track Resources

Visual Studio Home Page :: http://www.microsoft.com/visualstudio/en-us

Jason Zander’s Blog :: http://blogs.msdn.com/b/jasonz/

Facebook :: http://www.facebook.com/visualstudio

Twitter :: http://twitter.com/#!/visualstudio

Somasegar’s Blog :: http://blogs.msdn.com/b/somasegar/

Resources

Connect. Share. Discuss.

http://europe.msteched.com

Learning

Microsoft Certification & Training Resources

www.microsoft.com/learning

TechNet

Resources for IT Professionals

http://microsoft.com/technet

Resources for Developers

http://microsoft.com/msdn

Evaluations

http://europe.msteched.com/sessions

Submit your evals online

© 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.

Why build Web APIs?