56
ASP.NET WEB API (ADVANCED COURSE) Trainer: Chalermpon Areepong Microsoft MVP : ASP.NET ASP.NET & MVC THAI DEVELOPERS GROUP www.fb.com/groups/mvcthaidev

ASP.NET WEB API Training

Embed Size (px)

Citation preview

Page 1: ASP.NET WEB API Training

ASP.NET WEB API (ADVANCED COURSE)

Trainer: Chalermpon Areepong

Microsoft MVP : ASP.NET

ASP.NET & MVC THAI DEVELOPERS GROUP

www.fb.com/groups/mvcthaidev

Page 2: ASP.NET WEB API Training

ABOUT ME

CHALERMPON AREEPONG : Nine (นาย)

I’m a web developer

Microsoft MVP ASP.NET for 7 years

Founders in ASP.NET & MVC Developers Thailand (MVCTHAIDEV)

Page 3: ASP.NET WEB API Training

AGENDA I

Web Technology Introduce

ASP.NET WEB API Introduct

ModelBinder and Custom

Formatter and Custom 

ODATA

Async Operation 

Performance Improvement

Page 4: ASP.NET WEB API Training

AGENDA II (OPTIONAL)

Async Operation 

Performance Improvement

Page 5: ASP.NET WEB API Training

WEB TECHNOLOGYINTRODUCE

Page 6: ASP.NET WEB API Training

HTTP

URI : [scheme]: [port]: //[host] /[path] [? query] Representation : Content or Data Media Type : application/json, application/xml, image/png

HTTP : Hypertext Transfer Protocol HTTP Messages

HTTP Request HTTP Response

HTTP Method GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH and TRACE

Page 7: ASP.NET WEB API Training

HTTP METHOD

Method Objection

GET Retrieves information from a resource. return 200 (OK)

POST Requests the server to create new one of entity without duplicate object. Return code 201 (Created) or 202 (Accepted)

PUT Requests the server to replace the state of the target resource at the specified URI with the enclosed entity. If an existing resource exists for the current representation, it should return a 200(OK) ,204 (No Content) ,201 (Created).

DELETE Requests the server to remove the entity located at the specified URI. Return code 200(completed), 202 (Accepted) or 204 (No Content).

PATCH Requests the server to do a partial update of the the entity at the specified URI. The content of the patch should have enough information that the server can use to apply the update. If the resource exists the server and can be updated, return 200(OK), 204 (No Content),201 (Created).

Page 8: ASP.NET WEB API Training

HTTP METHOD

Method Objection

HEAD Identical to a GET only it returns headers and not the body.

OPTIONS Requests the server to return information about it’s capabilities. Most commonly it returns an Allow header specifying which HTTP methods are supported, though the spec leaves it completely open ended. For example it is entirely feasible to list which media types the server supports. OPTIONS can also return a body supplying further information that cannot be represented in the headers.

TRACE Requests the server to return back the request it received. The server will return the entire request message in the body with a Content-Type of "message/http". This is useful for diagnostics as clients can see which proxies the request passed through and how the request may have been modified by intermediaries.

CONNECT

Converts the request connection to a TCP Tunnel (HTTPS, websokets)

Page 9: ASP.NET WEB API Training

WEB COMMUNICATION

Web Server

GET

Response

GET https://www.facebook.com/groups/mvcthaidev HTTP/1.1method: GETaccept-encoding: gzip,deflate,sdchurl: /groups/mvcthaidevhost: www.facebook.comaccept-language: en-US,en;q=0.8user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8version: HTTP/1.1scheme: https

HTTP/1.1 200 OKcache-control: private, no-cache, no-store, must-revalidatecontent-encoding: gzipcontent-type: text/html; charset=utf-8date: Sat, 25 May 2013 08:21:01 GMTexpires: Sat, 01 Jan 2000 00:00:00 GMTp3p: CP="Facebook does not have a P3P policy. Learn why here: http://fb.me/p3p"pragma: no-cacheset-cookie: wd=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/; domain=.facebook.com; httponlystatus: 200strict-transport-security: max-age=60version: HTTP/1.1x-content-type-options: nosniffx-fb-debug: ERdqB2SxAcgCR0CJZG4+D200CnnoJPJV8k+R1bKkdi0=x-frame-options: DENYx-xss-protection: 0

Output : <!DOCTYPE html><html lang="en" id="facebook" class="no_js"> …………………………

Page 10: ASP.NET WEB API Training

WEB COMMUNICATION

Web Server

POST

Response

POST https://www.facebook.com/ajax/chat/imps_logging.php HTTP/1.1origin: https://www.facebook.commethod: POSTaccept-encoding: gzip,deflate,sdchurl: /ajax/chat/imps_logging.phphost: www.facebook.comaccept-language: en-US,en;q=0.8user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36content-type: application/x-www-form-urlencodedaccept: */*referer: https://www.facebook.com/groups/mvcthaidevx-svn-rev: 826852version: HTTP/1.1content-length: 242scheme: https

HTTP/1.1 200 OKcache-control: private, no-cache, no-store, must-revalidatecontent-encoding: gzipcontent-type: application/x-javascript; charset=utf-8date: Sat, 25 May 2013 08:21:05 GMTexpires: Sat, 01 Jan 2000 00:00:00 GMTpragma: no-cachestatus: 200strict-transport-security: max-age=60version: HTTP/1.1x-content-type-options: nosniffx-fb-debug: IPFu6HhUMaNDxBAvHb94M96B0QjjrZ7YeMdmBL4ArLQ=x-frame-options: DENYx-xss-protection: 0

Input: Form datasource: periodical_impssorted_list: 1321490013,1059545685,100000164752579,1093746402,100000165125475list_availability: 2,2,3,2,2__user: 712879509__a: 1__dyn: 7n8ahyj35CFwXAw__req: 1fb_dtsg: AQD81QbAphstamp: 16581685649819865213

Page 11: ASP.NET WEB API Training

HTTP STATUS CODE

Range Definition Ref Link

1xx The request has been received and processing is continuing.

http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-21#section-7.2

2xx The request has been accepted, received and understood.

http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-21#section-7.3

3xx Further action is required to complete the request.

http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-21#section-7.4

4xx The request is invalid and cannot be completed.

http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-21#section-7.5

5xx he server has failed trying to complete the request

http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-21#section-7.6

Page 12: ASP.NET WEB API Training

HTTP MEDIA FORMATS

JSON

XML

Form Data

Image

Others https://en.wikipedia.org/wiki/Internet_media_type

Page 13: ASP.NET WEB API Training

JSON (JAVASCRIPT OBJECT NOTATION)

Open standard

Text Based format

Lightweight than XML

Human readable

Derived from JavaScript object

Content Type = application/json

Extension *.json

Page 14: ASP.NET WEB API Training

JSON (JAVASCRIPT OBJECT NOTATION)

JavaScript object

JSON

var customer = { fullname : “PeeMark PraKhaNhong”, age : 500 , contacts : [ { mobileno: “025329000”, email : “[email protected]” } ] }

{ “fullname” : “PeeMark PraKhaNhong”, “age” : 500 , “contacts” : [ { “mobileno”: “025329000”, “email” : “[email protected]” } ] }

Page 15: ASP.NET WEB API Training

XML (EXTENSIBLE MARKUP LANGUAGE)

Unicode Support

Human and Machine Readable

Markup language like HTML <name>…</name>

Content Type = text/xml, application/xml text/xml if not specified encode will use ASCII is default application/xml used encode in document

<Person> <FullName>PeeMark PraKhaNhong</FullName> <Age>500</Age> <Contacts> <Contact MobileNo=“025329000” Email= “[email protected]” ></Contact> </Contacts></Person>

Page 16: ASP.NET WEB API Training

FORM DATA

Content-Type : application/x-www-form-urlencoded

Send by Form Submit

Format as Url Encode

Encoded : FullName=PeeMark%20PraKhaNhong&Age=500&MobileNo=025329000&Email=mark%40gmail.com

Decoded:FullName=PeeMark PraKhaNhong&Age=500&MobileNo=025329000&[email protected]

Page 17: ASP.NET WEB API Training

ASP.NET WEB API INTRODUCE

Page 18: ASP.NET WEB API Training

WHAT’S ASP.NET WEB API

HTTP Service

Service based on HTTP Protocol GET, POST, PUT, DELETE

No Proxy Class for client

Support Data Format : Form Data, JSON, XML and Custom

Support all clients are based on HTTP

Combine ASP.NET

Page 19: ASP.NET WEB API Training

WHY ASP.NET WEB API?

If we need a Web Service and don’t need SOAP, then ASP.Net Web API is very useful.

Web API - Used to build simple, non-SOAP-based HTTP Services on top of existing WCF message pipeline.

Web API - No need for configurable like WCF REST services

Web API - No need for Data contracts

Web API - Could create fully blown REST Services

Simple service creation with Web API.

Web API is focused at one thing, being easy to define and expose and consume, while also facilitating doing things in a RESTful way.

Web API is light weight architecture.

Page 20: ASP.NET WEB API Training

CLIENTS

Page 21: ASP.NET WEB API Training

WEB SERVICE TECHNOLOGY COMPARISON

Abilities ASP.NET WEB API WCF

Transport Channel HTTP(s) TCP, UDP, MSMQ, NamedPipes, HTTP(s), Custom

Protocol HTTP WS-*

Types CLR Types DataContract

Message format Text (xml, json) SOAP+XML

Service Interface HttpMethod, UrlPattern Service Contract

State management Stateless Stateless with per call

Cache Built-n to HTTP Prefer application control

Handled by application

Error Handling Exceptions, HTTP Status codes filters

Faults, Behaviors

Hosting IIS, Self Host IIS, Self Host

Client IApiExplorerShared Libraries

Proxy ClassShared Libraries

Page 22: ASP.NET WEB API Training

WCF => ASP.NET WEB API

WCF Web API ASP.NET Web API

Service => Web API controller

Operation => Action

Service contract => n/a

Endpoint => n/a

URI Template => ASP.NET Routing

Message handlers => Same

Formatters => Same

Operation handlers => Filters, model binders

Page 23: ASP.NET WEB API Training

LAB1BASIC ASP.NET WEB API

ASP.NET WEB API

Page 24: ASP.NET WEB API Training

LAB1BASICS

HTTP METHOD

HTTP MESSAGE

ROUTE

Page 25: ASP.NET WEB API Training

HTTP METHODS

Test the API from JavaScript client

Page 26: ASP.NET WEB API Training

HTTP MESSAGE

Request : HttpRequestMessage : represent for http request message information

Response HttpResponseMessage : return data and managed http header

information Object/Value : return data and when error will throw the exception. HttpResponseException : Http response message with 404(default)

Page 27: ASP.NET WEB API Training

HTTP MESSAGE

Open fiddler and click Composer Tab

1. GET http://localhost:7415/api/HttpMessages and Execute

2. route to GetAll() action

3. Test other method Get/Id, Post, Put, Delete

Page 28: ASP.NET WEB API Training

ROUTE

Like MVC App

Default route is api/{controller}/{id}

Add action to route like a MVC App api/{controller}/{action}/{id}

Force Action name with [ActionName(“name”)] to support {action}

Page 29: ASP.NET WEB API Training

LAB2PIPELINE PROCESS

Message handler

Page 30: ASP.NET WEB API Training

PIPELINE PROCESS

Message Handler is pre-post processing for Http Request and Response

Changing the request HTTP method

Adding a response header

Logging, Tracing

Page 31: ASP.NET WEB API Training

PIPELINE PROCESS TEST

Page 32: ASP.NET WEB API Training

LAB3FORMATTER AND MODEL BINDING

ASP.NET WEB API

Page 33: ASP.NET WEB API Training

FORMATTER AND MODEL BINDING

URI => ModelBinder, ValueBinder

Entity-Body => Formatter

URI, HEADER, Entity-body => custom format

Page 34: ASP.NET WEB API Training
Page 35: ASP.NET WEB API Training

TEST MODELBINDER

Page 36: ASP.NET WEB API Training

TEST MODEL VALIDATE

Page 37: ASP.NET WEB API Training

LAB4ODATA

ASP.NET WEB API

Page 38: ASP.NET WEB API Training

ODATA OPTION QUERY

Option Description

$filter Filters the results, based on a Boolean condition.

$inlinecount Tells the server to include the total count of matching entities in the response. (Useful for server-side paging.)

$orderby Sorts the results.

$skip Skips the first n results.

$top Returns only the first n the results.

Page 39: ASP.NET WEB API Training

ODATA QUERY TEST

http://localhost:24556/api/meetings

http://localhost:24556/api/meetings?$filter=Leader%20eq%20%27Mark%20Nichols%27 (Leader eq ‘Mark Nichols’)

http://localhost:24556/api/meetings?$top=2

http://localhost:24556/api/meetings?$filter=MeetingDate%20eq%20datetime%272013-01-17%27 MeetingDate eq datetime’2013-01-17′

Page 40: ASP.NET WEB API Training

ODATA QUERY RESULT

Page 41: ASP.NET WEB API Training

LAB6ASYNC OPERATION

ASP.NET WEB API

Page 42: ASP.NET WEB API Training

ASYNC IN WEB API

async = Asynchronous in easy way

async requires await

async support in .NET 4.5 only

.NET 4.5 provides a lot of new asynchronous methods

Page 43: ASP.NET WEB API Training

ASYNC RESULT

Page 44: ASP.NET WEB API Training

LAB7SECURITY

Token Validation

Page 45: ASP.NET WEB API Training

AUTHENTICATION SECURITY

SSL

All of IIS authentications

OAuth2.0

OpenID

Certificate’s Client Request

FormAuthentication

Page 46: ASP.NET WEB API Training

BASIC AUTHENTICATION SECURITY

Easy solution for internet application SSL + Basic Authentication + ASP.NET MembershipProvider

Pros Easy

Cons Username/Password encode to based 64

Page 47: ASP.NET WEB API Training

BASIC AUTHENTICATION SECURITY

Page 48: ASP.NET WEB API Training

TOKEN VALIDATION

Token Validation = AntiForgery

Page 49: ASP.NET WEB API Training

DEMO TOKEN VALIDATION

Page 50: ASP.NET WEB API Training

LAB7PERFORMANCE IMPOVEMENT

Message Compression

HiPerf JavaScript Serializer

Page 51: ASP.NET WEB API Training

MESSAGE COMPRESSION

You can enable this feature in IIS7 or later

Page 52: ASP.NET WEB API Training

HI-PERFORMANCE JAVASCRIPT SERIALIZER

ServiceStack.Text is best of faster javascriptserializer

Create our new Custom Json Formatter and replace old

Page 53: ASP.NET WEB API Training

HI-PERFORMANCE JAVASCRIPT SERIALIZER

Page 54: ASP.NET WEB API Training

CONCLUSION

New way for WEB Service based on HTTP

Best the way for HTTP Service

Support all of the HTTP Clients

Extensibility, we able to customize all of the modules

Closely with ASP.NET MVC

It’s OPENSOURCE http://aspnetwebstack.codeplex.com/

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

Page 55: ASP.NET WEB API Training

THANK YOU

Page 56: ASP.NET WEB API Training

REAL WORLD IMPLEMENTATION BY

CASE STUDYASP.NET WEB API Advanced course II

soon…