Excellent rest using asp.net web api

Preview:

DESCRIPTION

Create REST and hypermedia services using the ASP.NET WebAPI.

Citation preview

Excellent REST using ASP.NET WebApi

Maurice de Beijer

2

Who am I?

• Maurice de Beijer• The Problem Solver• Microsoft Integration MVP• DevelopMentor instructor• Twitter:@mauricedb• Blog: http://msmvps.com/blogs/theproblemsolver/ • Web: http://www.HTML5Support.nl • E-mail: mauricedb@develop.com

3

What are we going to cover?

• What is REST?• What is ASP.NET WebAPI• Hypermedia

4

What is REST?

Representational State Transfer (REST) is an architectural style that abstracts

the architectural elements within a distributed hypermedia system.

Wikipedia

5

What is REST?

• First conceived by Roy Thomas Fielding– Part of his doctoral thesis from 2000– One of the original authors of the Hypertext Transfer Protocol

-- HTTP/1.0• A way of creating “web services”

– Based on the HTTP standard

6

Hypertext Transfer Protocol

The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed,

collaborative, hypermedia information systems. It is a generic, stateless, protocol which can be

used for many tasks beyond its use for hypertext.

The Internet Engineering Task Force

7

Richardson Maturity Model

8

ASP.NET WebAPI

ASP.NET Web API is a framework that makes it easy to build HTTP and REST services using

the .NET framework.

9

WebAPI Controllers

• An ApiController does the work– Access to the HTTP Request and Response

• Use ModelBinding to ease working with resources– But also provides HttpRequestMessage for low level access

10

WebAPI Controllers

• Lots of control about sending resources to the client– HttpResponseMessage– Content negotiation

• Set any HTTP header you like– Caching– Optimistic concurrency

11

WebAPI Controllers

public class DemoController : ApiController{ // GET api/demo public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }}

public class DemoController : ApiController{ // GET api/demo public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }}

12

WebAPI Routes

• Couple an incoming URL to an ApiController– Just like with ASP.NET MVC

• Create as many as you like– The ordering is important!

13

WebAPI Routes

public static void Register(HttpConfiguration config){ config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );}

public static void Register(HttpConfiguration config){ config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );}

14

Content negotiation

• What resource we send != how we send it– JSON of XML: a book resource is still a book resource

15

MediaTypeFormatter

• The media type specifies the serialization format– JSON, XML, Word, PDF, VCard etc

• The MediaTypeFormatter (de)serializes– HTTP <> CLR type

• Content negotiation determines the serialized format– The client uses the HTTP Accept header

16

MediaTypeFormatter

public class CustomersTextFormatter : BufferedMediaTypeFormatter{ public CustomersTextFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/text")); }

public override bool CanWriteType(Type type) { return typeof(IEnumerable<Customer>).IsAssignableFrom(type); }

public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)

{ // ... }}

public class CustomersTextFormatter : BufferedMediaTypeFormatter{ public CustomersTextFormatter() { SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/text")); }

public override bool CanWriteType(Type type) { return typeof(IEnumerable<Customer>).IsAssignableFrom(type); }

public override void WriteToStream(Type type, object value, Stream writeStream, HttpContent content)

{ // ... }}

17

HTTP Methods

• HTTP supports many HTTP Methods– With HTML we only use two

• The HTTP Method determines our goal– Just like the database CRUD actions

18

HTTP Methods

Aktie HTTP Method

Create POST

Read GET

Update (completly replace) PUT

Update (partial replace) PATCH

Delete DELETE

19

WebAPI HTTP Methods

public class DemoController : ApiController { // GET api/demo public IEnumerable<string> Get()

// GET api/demo/5 public string Get(int id)

// POST api/demo public void Post([FromBody]string value)

// PUT api/demo/5 public void Put(int id, [FromBody]string value)

// DELETE api/demo/5 public void Delete(int id)}

public class DemoController : ApiController { // GET api/demo public IEnumerable<string> Get()

// GET api/demo/5 public string Get(int id)

// POST api/demo public void Post([FromBody]string value)

// PUT api/demo/5 public void Put(int id, [FromBody]string value)

// DELETE api/demo/5 public void Delete(int id)}

20

Hypermedia - Roy T. Fielding

Hypermedia is defined by the presence of application control information embedded within, or

as a layer above, the presentation of information. Distributed hypermedia allows the presentation and

control information to be stored at remote locations.

Roy T. Fielding

21

Richardson Maturity Model

22

The OData Protocol

• Open Data Protocol (OData)– A hypermedia web protocol for retrieving and updating data.– Based on the W3C AtomPub standard

• Can include metadata• WCF Data Services is an implementation

23

OData metadata

• An OData service can return metadata– http://www.nerddinner.com/Services/OData.svc/$metadata

• Enables generic clients like PowerPivot for Excel

24

ASP.NET WebAPI and OData

• Standard ApiController’s support basic querying– $filter– $orderby– $skip– $take– $expand and $select support coming soon

• Needs to be explicitly enabled

public static void Register(HttpConfiguration config){ // Other config

config.EnableQuerySupport();}

public static void Register(HttpConfiguration config){ // Other config

config.EnableQuerySupport();}

25

OData queries

public class CustomerController : ApiController{ private NorthwindEntities db =

new NorthwindEntities();

// GET api/Default2 [Queryable(PageSize=10)] public IQueryable<Customers> GetCustomers() { return db.Customers; }}

public class CustomerController : ApiController{ private NorthwindEntities db =

new NorthwindEntities();

// GET api/Default2 [Queryable(PageSize=10)] public IQueryable<Customers> GetCustomers() { return db.Customers; }}

26

OData hypermedia controller

• The EntitySetController class can be used for more complete hypermedia support

• Build in support for Entity Framework Code First– But we can use any type we want

27

OData metadata support

28

OData hypermedia controller

public class HypermediaBooksController : EntitySetController<Book, int>{ private readonly IBooksRepository _repo = new BooksRepository();

// GET odata/hypermediaBooks public override IQueryable<Book> Get() { return _repo.GetBooks().AsQueryable(); }

// GET odata/hypermediaBooks(3) protected override Book GetEntityByKey(int key) { return _repo.GetBook(key); }}

public class HypermediaBooksController : EntitySetController<Book, int>{ private readonly IBooksRepository _repo = new BooksRepository();

// GET odata/hypermediaBooks public override IQueryable<Book> Get() { return _repo.GetBooks().AsQueryable(); }

// GET odata/hypermediaBooks(3) protected override Book GetEntityByKey(int key) { return _repo.GetBook(key); }}

29

OData hypermedia routing

public static void Register(HttpConfiguration config){ // Other config

ODataModelBuilder modelBuilder = new ODataConventionModelBuilder(); modelBuilder.EntitySet<Book>("hypermediaBooks");

Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel(); config.Routes.MapODataRoute("ODataRoute", "odata", model);}

public static void Register(HttpConfiguration config){ // Other config

ODataModelBuilder modelBuilder = new ODataConventionModelBuilder(); modelBuilder.EntitySet<Book>("hypermediaBooks");

Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel(); config.Routes.MapODataRoute("ODataRoute", "odata", model);}

30

Recommended reading

31

Conclusion

• ASP.NET WebAPI makes REST “easy”– Even though sometimes ASP.NET MVC is enough

• Think about hypermedia– Especially when the service is publicly available

32

Questions

?The presentation and source code will be available

http://msmvps.com/blogs/theproblemsolver/

Recommended