Excellent rest using asp.net web api

32
Excellent REST using ASP.NET WebApi Maurice de Beijer

description

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

Transcript of Excellent rest using asp.net web api

Page 1: Excellent rest using asp.net web api

Excellent REST using ASP.NET WebApi

Maurice de Beijer

Page 2: Excellent rest using asp.net web api

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: [email protected]

Page 3: Excellent rest using asp.net web api

3

What are we going to cover?

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

Page 4: Excellent rest using asp.net web api

4

What is REST?

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

the architectural elements within a distributed hypermedia system.

Wikipedia

Page 5: Excellent rest using asp.net web api

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

Page 6: Excellent rest using asp.net web api

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

Page 7: Excellent rest using asp.net web api

7

Richardson Maturity Model

Page 8: Excellent rest using asp.net web api

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.

Page 9: Excellent rest using asp.net web api

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

Page 10: Excellent rest using asp.net web api

10

WebAPI Controllers

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

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

Page 11: Excellent rest using asp.net web api

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" }; }}

Page 12: Excellent rest using asp.net web api

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!

Page 13: Excellent rest using asp.net web api

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 } );}

Page 14: Excellent rest using asp.net web api

14

Content negotiation

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

Page 15: Excellent rest using asp.net web api

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

Page 16: Excellent rest using asp.net web api

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)

{ // ... }}

Page 17: Excellent rest using asp.net web api

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

Page 18: Excellent rest using asp.net web api

18

HTTP Methods

Aktie HTTP Method

Create POST

Read GET

Update (completly replace) PUT

Update (partial replace) PATCH

Delete DELETE

Page 19: Excellent rest using asp.net web api

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)}

Page 20: Excellent rest using asp.net web api

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

Page 21: Excellent rest using asp.net web api

21

Richardson Maturity Model

Page 22: Excellent rest using asp.net web api

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

Page 23: Excellent rest using asp.net web api

23

OData metadata

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

• Enables generic clients like PowerPivot for Excel

Page 24: Excellent rest using asp.net web api

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();}

Page 25: Excellent rest using asp.net web api

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; }}

Page 26: Excellent rest using asp.net web api

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

Page 27: Excellent rest using asp.net web api

27

OData metadata support

Page 28: Excellent rest using asp.net web api

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); }}

Page 29: Excellent rest using asp.net web api

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);}

Page 30: Excellent rest using asp.net web api

30

Recommended reading

Page 31: Excellent rest using asp.net web api

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

Page 32: Excellent rest using asp.net web api

32

Questions

?The presentation and source code will be available

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