SlideShare a Scribd company logo
ASP.NET Web API
and HTTP Fundamentals
Ido Flatow

Senior Architect
Microsoft MVP
SELA Group

@idoFLATOW
http://bit.ly/flatow-blog

This presentation:
http://sdrv.ms/1eKAsRd
ASP.NET WEB API AND HTTP FUNDAMENTALS

CRAMMING YOUR BRAINS WITH
HTTP & ASP.NET WEB API


HTTP Fundamentals via Web API



Hosting



HTTP Messages



HTTP.SYS



URIs



IIS 101



Routing



HTTP compression



Verbs



Persisted Connections



Controllers and Actions



Web API Self Hosting



Status Codes



HttpRequestMessage
HttpResponseMessage



Error Handling



Content Negotiation



Media Type Formatters



OData



Validations



Dependency Resolver

www.devconnections.com



More HTTP and Web API


Caching



Concurrency



Security



Streaming



WebSockets & SignalR

2
ASP.NET WEB API AND HTTP FUNDAMENTALS

ABOUT ME



Senior architect, Sela Group
Co-author of:






WCF 4 – Microsoft official course





Developing Windows Azure and Web Services –
Microsoft official course
Pro .NET Performance – Apress

Microsoft MVP
Focus on server, services, and cloud
technologies
Manager of the Israeli Web Developers User
Group

www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS

WHY IS HTTP IMPORTANT?


HTTP is a first class application layer protocol



Unlike other protocols it was created to
support a single information system



That system happened to be the largest and
main information system of the human race:

www.devconnections.com

4
ASP.NET WEB API AND HTTP FUNDAMENTALS

NO REALLY, WHY?
 Today's




systems face new challenges:

Internet scale applications

Cloud-based applications

www.devconnections.com

5
ASP.NET WEB API AND HTTP FUNDAMENTALS

NO REALLY, WHY?
 Today's


systems face new challenges:

Broader reach of clients

www.devconnections.com

6
ASP.NET WEB API AND HTTP FUNDAMENTALS

WHAT ABOUT ASP.NET WEB API?
 The

.NET platform never had a first class
framework for HTTP-based services

 WCF

was created as a SOAP-based
framework and never really matured to
support HTTP

www.devconnections.com

7
ASP.NET WEB API AND HTTP FUNDAMENTALS

THE HISTORY OF ASP.NET WEB API
6 Preview Versions

WCF Web API
on CodePlex

WCF WebHttp
Binding (.NET 4)

www.devconnections.com

ASP.NET Web API 4
Release

ASP.NET is
Open Source

ASP.NET Web API 2
Release Candidate

ASP.NET Web API
(Beta)

8
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP MESSAGES 101
 HTTP

is a first class application protocol:



Widely supported across platforms and devices



Scalable



Simple

 Uses

the request-response messaging pattern

 Define

resource-based semantics and not
RPC (Remote Procedure Call) or methods

www.devconnections.com

9
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP REQUEST MESSAGES
GET http://localhost:2300/api/agents/Bond HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: en-US,en;q=0.7,he;q=0.3
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2;
WOW64; Trident/6.0)
Accept-Encoding: gzip, deflate
Host: localhost:2300
DNT: 1
Connection: Keep-Alive

www.devconnections.com

10
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP RESPONSE MESSAGES
HTTP/1.1 200 OK
Cache-Control: public, max-age=300
Content-Type: application/json; charset=utf-8
ETag: "1"
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
Date: Mon, 19 Nov 2012 17:49:40 GMT
Content-Length: 142
{

}

"Id": "Bond",
"FullName": "James Bond",
"Alias": "007",
"Version": 1,
"Image": "http://localhost:2300/api/agents/Bond.jpg"

www.devconnections.com

11
ASP.NET WEB API AND HTTP FUNDAMENTALS

URIS
 HTTP

is not an RPC protocol

 HTTP

uses URIs to identify resources over
the network

 An

HTTP URI has the following basic
structure:
http://theagency.com:8080/agents?id=1
Schema

www.devconnections.com

Host

Port

Absolute
Path

Query

12
ASP.NET WEB API AND HTTP FUNDAMENTALS

CLEAN URLS AND ASP.NET


Using clean URLs can be a problem with IIS



IIS needs extensions to map requests to handlers



Without extensions, IIS is lost



ASP.NET Routing to the rescue with UrlRoutingModule



It’s all about patterns… and mapping them to handlers



The starting point of MVC, Dynamic Data, and Web API



System.Web.Routing.RouteTable.Routes.MapHttpRoute

RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
www.devconnections.com

13
ASP.NET WEB API AND HTTP FUNDAMENTALS

THE BASICS OF WEB API - ROUTING
DEMO

www.devconnections.com

14
ASP.NET WEB API AND HTTP FUNDAMENTALS

ROUTING WITH ATTRIBUTES
 Why

attributes over convention?



Child (sub) resources



Multiple type of parameters or return values



Versioning of actions and controllers

 Start


by enabling attribute routing

config.MapHttpAttributeRoutes();

[RoutePrefix("api/agents/{agentId}")]
public class ObservationsController : ApiController
{
// GET api/agents/bond/observations
[HttpGet("observations/{date}")]
public Observation Get(string agentId, DateTime date) { ... }
}

www.devconnections.com

15
ASP.NET WEB API AND HTTP FUNDAMENTALS

VERBS
 HTTP

defines a set of Methods or Verbs that
add an action-like semantics to requests

 Verbs

are defined as the first segment of the
request-line:
GET http://localhost:4392/travelers/1 HTTP/1.1

 There

are eight verbs defined in HTTP 1.1:

GET
POST
PUT
DELETE
www.devconnections.com

HEAD
OPTIONS
TRACE
CONNECT
16
ASP.NET WEB API AND HTTP FUNDAMENTALS

3, 2, 1, ACTIONS!
 Actions

are matched by HTTP verb
public names and the existence of parameters
class ProductsController : ApiController
{
public IEnumerable<Product> GetProducts() {...}
public Product GetProductById(int id) {...}
public HttpResponseMessage PostProduct(Product product) {...}
}

GET api/products
GET api/products/42
POST api/products
www.devconnections.com

DELETE api/products/42
ASP.NET WEB API AND HTTP FUNDAMENTALS

HANDLING VERBS IN ASP.NET WEB API
DEMO

www.devconnections.com

18
ASP.NET WEB API AND HTTP FUNDAMENTALS

STATUS CODES


Status codes describe the result of the server’s effort
to satisfy the request



Passed in the response's status-line as three digit
alongside a textual description called reason phrase



HTTP has five different categories of status-codes:


1xx – Informational (100 / 101)



2xx – Success

(200 – 206)



3xx – Redirection

(300 – 307)



4xx – Client Error

(400 – 417)



5xx – Server Error

(500 – 505)

www.devconnections.com

19
ASP.NET WEB API AND HTTP FUNDAMENTALS

STATUS CODE EXAMPLES


404?



401?



304?



503?



500?



200?



301?



302?

www.devconnections.com

20
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP RESPONSE MESSAGE
 Returning

an HttpResponseMessage allows
more control over the response, including:


Status code



HTTP headers



Entity body

public HttpResponseMessage CreateAgent(Agent agent)
{
agent = _repository.Add(agent);
var response =
Request.CreateResponse<Agent>(HttpStatusCode.Created, agent);
response.Headers.Location = GetAgentLocation(agent.Id);
return response;
}
www.devconnections.com

21
ASP.NET WEB API AND HTTP FUNDAMENTALS

HANDLING STATUS CODES
DEMO

www.devconnections.com

22
ASP.NET WEB API AND HTTP FUNDAMENTALS

ERROR HANDLING


In HTTP services errors are handled by





Returning an appropriate status code
Returning an entity body explaining the error
(when applicable)

Web API allows you to handle exceptions by


Return an HttpResponseMessage with
appropriate status code (404, 500 …)



Throw an HttpResponseException



Create a general exception handler by using
Filters

www.devconnections.com

23
ASP.NET WEB API AND HTTP FUNDAMENTALS

HANDLING ERRORS
DEMO

www.devconnections.com

24
ASP.NET WEB API AND HTTP FUNDAMENTALS

MEDIA TYPES
 HTTP

was originally designed to transfer
Hypertext

 Hypertext

documents contain references to
other resources including images, video, etc.

 Multipurpose

Internet Mail Extensions (MIME)
Types or Media-types allow HTTP to express
different formats:
text/html; charset=UTF-8
Type

www.devconnections.com

Subtype

Type specific parameters
25
ASP.NET WEB API AND HTTP FUNDAMENTALS

CONTENT NEGOTIATION
 HTTP

defines a process to best match the
server’s response to the client’s expectation

 Negotiation

can be done using:



Headers:
Accept, Accept- Language, Accept- Charset,
Accept-Encoding



URI:
File extensions (.jpeg, .html), host-name: (com, org),
path and query

www.devconnections.com

26
ASP.NET WEB API AND HTTP FUNDAMENTALS

MEDIA TYPE FORMATTERS
 ASP.NET

Web API uses Media Type Formatters to
control serialization

 Each

media type formatter is associated with a
media type, file extension, or query string

 The

host is configured with a collection of
MediaTypeFormatter objects

 Create

custom formatters by deriving from:



MediaTypeFormatter – asynchronous read/write



BufferedMediaTypeFormatter – synchronous read/write

www.devconnections.com

27
ASP.NET WEB API AND HTTP FUNDAMENTALS

CONTENT NEGOTIATION IN WEB API
DEMO

www.devconnections.com

28
ASP.NET WEB API AND HTTP FUNDAMENTALS

VALIDATING USER INPUT


Use System.ComponentModel.DataAnnotations
on entity classes to add validation rules



Validation rules can be check by calling
ModelState.IsValid



When validation fails, return a Bad Request (400)



ModelState is a dictionary of property name &
errors, use it to construct a meaningful response

www.devconnections.com

29
ASP.NET WEB API AND HTTP FUNDAMENTALS

VALIDATING USER INPUT
public class Contact {
[Required]
public string FullName { get; set;}
[Email]
public string Email { get; set;}
}
if (!this.ModelState.IsValid) {
var errors = this.ModelState.Where(s => s.Value.Errors.Count > 0)
.Select(s => new KeyValuePair<string, string>
(s.Key, s.Value.Errors.First().ErrorMessage));
response = Request.CreateResponse(
HttpStatusCode.BadRequest, errors);

}

www.devconnections.com

30
ASP.NET WEB API AND HTTP FUNDAMENTALS

VALIDATING USER INPUT
DEMO

www.devconnections.com

31
ASP.NET WEB API AND HTTP FUNDAMENTALS

ODATA QUERYABLE ACTIONS
 The

Open Data Protocol (OData) provides a
RESTful standard for exposing data models

 OData

uses URIs to perform query operations:



Entity projection – $select, $expand



Sorting – $orderby



Entity sub-setting – $top, $skip



Filtering – $filter, logical operators: eq, ne, gt, lt

www.devconnections.com

32
ASP.NET WEB API AND HTTP FUNDAMENTALS

DEFINING ODATA ACTIONS


Install the Microsoft.AspNet.WebApi.OData NuGet
package



Define an action with the following characteristics:


Returns IQueryable<T> or IEnumerable<T>



Decorated with the [Queryable] attribute

[Queryable]

public IQueryable<Agent> GetAgents()
{
}

www.devconnections.com

33
ASP.NET WEB API AND HTTP FUNDAMENTALS

WEB API AND ODATA
[Queryable]
public IQueryable<Agent> GetAgents()
{
return repository.GetAll().AsQueryable();
}
api/agents?$orderby=Name
api/agents?$skip=10
api/agents?$skip=50&$top=10

api/agents?$filter=salary gt 50000
www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS

ODATA ACTIONS
DEMO

www.devconnections.com

35
ASP.NET WEB API AND HTTP FUNDAMENTALS

ODATA MODELS
 OData

also provides a mechanism for
exposing entity models:


Publishing the models metadata



Exposing relations between entities using the
Atom media-type

www.devconnections.com

36
ASP.NET WEB API AND HTTP FUNDAMENTALS

CREATING AND EXPOSING ODATA
MODELS
 Exposing

an OData model requires the
following configuration:


Creating an EDM model using the
ODataConventionModelBuilder class



Adding a route using the MapODataRoute
method

 In

addition, any controller exposed in the
model should derive from the
ODataController or
EntitySetController<TEntity, TKey> classes

www.devconnections.com

37
ASP.NET WEB API AND HTTP FUNDAMENTALS

CONSUMING ODATA SERVICES


Add a service reference to the OData service



Create a new instance of the generated
Container class



Use LINQ to query the container

var client = new MyODataService.Container(new Uri("…"));
var agent = (from a in client.Agents
where a.Id == "Bond"
select a).Single();

www.devconnections.com

38
ASP.NET WEB API AND HTTP FUNDAMENTALS

ODATA MODELS
DEMO

www.devconnections.com

39
ASP.NET WEB API AND HTTP FUNDAMENTALS

DEPENDENCY RESOLVER
AND THE API CONTROLLER


To be testable, the ApiController should
support dependency injection



Web API supports dependency injection with
the IDependencyResolver interface



Implement your custom resolver or use it to
wrap a known IoC Container (Castle, Unity,
MEF, Ninject…)



Register the dependency resolver through
Web API global configuration



And Voilà!

www.devconnections.com

40
40
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP.SYS, WHAT’S THAT?


It’s the thing that handles HTTP on your machine



It’s a kernel mode device driver



Ever since Windows XP SP2 / Windows Server 2003



Responsible of



Kernel mode SSL (full support as of Windows Server 2008)



Caching responses in kernel mode





Routing requests to the correct application

Implementing QoS, such as connection limits and timeouts

Want to know more? netsh http show

www.devconnections.com

41
ASP.NET WEB API AND HTTP FUNDAMENTALS

IIS 101



Web application hosting
Comes in two flavors






IIS Express

Full IIS (or simply IIS)

Provides


Reliability



Manageability



Security



Performance



Scalability

www.devconnections.com

42
ASP.NET WEB API AND HTTP FUNDAMENTALS

ENABLING COMPRESSION WITH IIS



Compression is something the client needs to
request
Requests are not normally compressed



Accept-Encoding: gzip,deflate
Server is not obligated to compress the response



Content-Encoding: gzip / deflate



IIS Compression
Modes
Dynamic
Compression
Static Compression
www.devconnections.com

Scenarios

Considerations

Small number of requests

Uses CPU and memory

Limited network bandwidth

Not cached

Improve transmission times

Can be cached

Graphic-heavy sites

Uses some CPU

43
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP PERSISTENT CONNECTION
IT’S ALIVE



Beginning with HTTP 1.1, clients and servers
must support persistent connections
Persistent is good



Fewer TCP connections = less congestion





Single connection can pipeline HTTP requests





Less simultaneous opened connections = less CPU

No re-handshaking = reduced latency

Send Connection: Keep-Alive in request and response
headers to keep the underlying TCP connection open
Connection is dropped if either end lacks sending the
Keep-Alive header – Implementation Dependent

www.devconnections.com

44
ASP.NET WEB API AND HTTP FUNDAMENTALS

KEEPING IT ALIVE!
DEMO

www.devconnections.com

45
ASP.NET WEB API AND HTTP FUNDAMENTALS

KEEP IT ALIVE, BUT FOR HOW LONG?







IIS by default adds Keep-Alive to every response
HTTP.SYS has a default timeout of 120 seconds for idle
connections
When expecting many clients with a small number of
request, Keep-Alive may have an overhead
For short visits, consider disabling Keep-Alive or reduce
the idle timeout to a couple of seconds (5? 2? 1?)
Use logs to check visits and frequency of idle
connections:


IIS log files: C:inetpublogsLogFiles



HTTP.SYS log files: %windir%system32LogFilesHTTPERR

www.devconnections.com

46
ASP.NET WEB API AND HTTP FUNDAMENTALS

WHO NEEDS IIS? WE HAVE SELF-HOSTING
IIS is the natural hosting environment for the
ASP.NET web stack, Web API included
 When IIS is not an option or unwanted, use a
self-hosted Web API
 Just follow three basic steps:





Create host configuration and routing rules





Install the Microsoft ASP.NET Web API Self Host
NuGet package
Start the self-hosted server

Under the covers, Web API self-hosting is
handled by WCF

www.devconnections.com

47
ASP.NET WEB API AND HTTP FUNDAMENTALS

CACHING
 HTTP

caches store copies of responses to
reduce network traffic

 HTTP

caches reduces call latency and
increases server throughput

 Caches

are a main factor for scalability
on the web

www.devconnections.com

48
ASP.NET WEB API AND HTTP FUNDAMENTALS

TYPES OF CACHES


Browser/Client Cache
Stores representations locally on the computer’s
hard drive



Proxy Cache
Corporates and ISPs provide shared proxies
providing shared cache on their network



Gateway (Reverse Proxy) Cache
Stores representations on behalf of the server.
Content Delivery Networks (CDNs) use gateway
cache distributed around the web

www.devconnections.com

49
ASP.NET WEB API AND HTTP FUNDAMENTALS

CONTROLLING CACHE
 HTTP

headers can be used to control
cache behaviors

 HTTP

provides method the avoid
staleness of cached data


Expiration



Validation



Invalidation

www.devconnections.com

50
ASP.NET WEB API AND HTTP FUNDAMENTALS

CONTROLLING CACHE
DEMO

www.devconnections.com

51
ASP.NET WEB API AND HTTP FUNDAMENTALS

ETAG: VERSIONING & CONCURRENCY





When caching content, we need to identify when
content has changed
The ETag (entity tag) header represents the version of
the content
ETags are sent to the client with the response, and are
re-sent to the server on subsequent requests
In the action, compare received and existing ETags,
and return either:





A new entity if they are different
An HTTP 304 (Not Modified) if they are identical

When updating entities using POST/PUT, use the ETag
for concurrency (version) checks

www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS

ETAG VERSIONING
public HttpResponseMessage Get(int id)
{
HttpResponseMessage response;
var etag = Request.Headers.IfNoneMatch.FirstOrDefault();
Agent agent = _manager.GetAgentById(id);
if (etag != null &&
etag.ToString().Replace(@"""", "") == agent.Version)
{
response = new HttpResponseMessage(HttpStatusCode.NotModified);
}
else
{
response = Request.CreateResponse(HttpStatusCode.OK, agent);
response.Headers.ETag = new EntityTagHeaderValue(
string.Format(@"""{0}""", agent.Version));
}
return response;
www.devconnections.com
53
}
ASP.NET WEB API AND HTTP FUNDAMENTALS

SECURITY


HTTP messages are clear text, in order to
have any form of secured connection they
must be encrypted



This is what SSL is for



Once encrypted there are still several
challenges remaining:


Authentication



Persisting authentication throughout the
conversation



Authorization

www.devconnections.com

54
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTPS - HOW SECURE SOCKETS LAYER WORKS
3. Client verifies certificate’s
authenticity
1. Client requests a secured session
2. Server responds with an X.509 certificate
4. Client sends a symmetric encryption key

(encrypted with the server’s public key)
6. Client and server exchange encrypted messages

(encrypted with the symmetric key)

5. Server decrypts the encryption
key with its private key
www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS

CLASSIC HTTP AUTHENTICATION


HTTP uses the Authorization header to pass
authentication data:

Authorization: Basic eWFuaXY6eWFuaXY=


According to specs, HTTP supports only two
schemas:





Basic (plain text)
Digest (hashed password)

Nowadays, it is common to find other schemas:


NTLM / Negotiate (Windows authentication)



Certificate



OAuth

www.devconnections.com

56
ASP.NET WEB API AND HTTP FUNDAMENTALS

BASIC AUTHENTICATION
DEMO

www.devconnections.com

57
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP STREAMING


Advantages



Message can be handled before received completely





Less large memory allocation and buffering
Connection can remain opened for a long time

Useful for





File download/upload
Live data feed (notifications, video streams, …)

It’s a chunking mechanism


Uses a persistent HTTP connection



The Content-Length HTTP header is omitted



Each chunk is sent as size + chunk



Chunk size can vary



Stream ends when last chunk is sent with size 0 (zero)

www.devconnections.com

58
ASP.NET WEB API AND HTTP FUNDAMENTALS

HTTP STREAMING AND WEB API


Reading a streamed request





Request.Content.ReadAsStreamAsync (File Stream )
Request.Content.ReadAsMultipartAsync (Multi-part
Stream)

Writing a streamed response


Do you want to pull from an existing stream? Or push
your own data down the stream?



Pull : StreamContent(inputStream)



Push: PushStreamContent(contentWritingAction)



When pushing data use Stream.Flush() to chunk

www.devconnections.com

59
ASP.NET WEB API AND HTTP FUNDAMENTALS

STREAMING WITH WEB API
DEMO

www.devconnections.com

60
ASP.NET WEB API AND HTTP FUNDAMENTALS

DUPLEX COMMUNICATION
WITH HTTP


HTTP is a request-response protocol



Updates are through server polling





Periodic polling (Anything new?)
Long polling (I’m waiting for you!)

Many disadvantages


Periodic polling inflicts high-latency on updates



Long polling is hard to implement



Can cause bandwidth overhead if used
improperly

www.devconnections.com

61
ASP.NET WEB API AND HTTP FUNDAMENTALS

WEBSOCKETS IN A GLANCE
 Bi-directional
 Supports

both HTTP and HTTPS (SSL)

 Accessible
 Supports

TCP channel (full-duplex)

through JavaScript API

cross-domain calls

 Client-side

- IE10, Chrome, Firefox, .NET 4.5

 Server-side

– IIS 8, ASP.NET 4.5, SignalR

 Standardization

www.devconnections.com

is still in progress!!
ASP.NET WEB API AND HTTP FUNDAMENTALS

ASP.NET SIGNALR 101
 Real-time,

over HTTP

persistent connection abstraction

 Useful

for dashboards & monitoring,
collaborative work, job progress, gaming…

 SignalR

works everywhere



WebSockets



Server Sent Events



Forever Frame



Long Polling

www.devconnections.com

63
ASP.NET WEB API AND HTTP FUNDAMENTALS

ASP.NET SIGNALR 101
 Supported

clients:



Desktop applications using .NET 4/4.5



Web browsers using JavaScript



Windows Store and Windows Phone Apps

 Supports

scaling servers to Web farm with
Windows Azure Service Bus, Redis, and SQL
Server

www.devconnections.com

64
ASP.NET WEB API AND HTTP FUNDAMENTALS

SIGNALR API, CHOOSE WHAT WORKS
FOR YOU
 Connections


Low level



Raw strings up and down (the “old way”)



Broadcast to all clients, groups, or individuals



Connect, reconnect & disconnect semantics

 Hubs


Built on top of connections



Client-Server and Server-Client RPC



Automatic client proxy generation for JavaScript

www.devconnections.com

65
ASP.NET WEB API AND HTTP FUNDAMENTALS

ASP.NET SIGNALR
DEMO

www.devconnections.com

66
ASP.NET WEB API AND HTTP FUNDAMENTALS

SO WHAT DID WE LEARN TODAY?


HTTP Fundamentals via Web API



Hosting

You are now an HTTP ninja
Rank 1. Just 4 more ranks to go!!


HTTP Messages



HTTP.SYS



URIs



IIS 101



Routing



HTTP compression



Verbs



Persisted Connections



Controllers and Actions



Web API Self Hosting



Status Codes



HttpRequestMessage
HttpResponseMessage



Error Handling



Content Negotiation



Media Type Formatters



OData



Validations



Dependency Resolver

www.devconnections.com



More HTTP and Web API


Caching



Concurrency



Security



Streaming



WebSockets & SignalR

67
ASP.NET WEB API AND HTTP FUNDAMENTALS

RESOURCES


HTTP




www.ietf.org/rfc/rfc2616.txt

REST




www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

ASP.NET Web API


www.asp.net/web-api



www.asp.net/web-api/videos





This Presentation:
sdrv.ms/1eKAsRd

webapibloggers.com (without www)

Fiddler


www.fiddler2.com



www.youtube.com/watch?v=7Tw5EHvTERc



“Debugging the Web with Fiddler”, Tuesday 2:00PM

www.devconnections.com

68
Ad

More Related Content

What's hot (20)

Understanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple Steps
Tessa Mero
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
C# web api
C# web apiC# web api
C# web api
Simplilearn
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
Avanade Nederland
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
Aniruddh Bhilvare
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
Ahmad Shah Hafizan Hamidin
 
What is Ajax technology?
What is Ajax technology?What is Ajax technology?
What is Ajax technology?
JavaTpoint.Com
 
Express JS Rest API Tutorial
Express JS Rest API TutorialExpress JS Rest API Tutorial
Express JS Rest API Tutorial
Simplilearn
 
Rest API
Rest APIRest API
Rest API
Rohana K Amarakoon
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
Prateek Tandon
 
REST API
REST APIREST API
REST API
Tofazzal Ahmed
 
Adobe AEM core components
Adobe AEM core componentsAdobe AEM core components
Adobe AEM core components
Lokesh BS
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
Antonio Severien
 
SOAP vs REST
SOAP vs RESTSOAP vs REST
SOAP vs REST
Mário Almeida
 
API 101 event.pdf
API 101 event.pdfAPI 101 event.pdf
API 101 event.pdf
AkankshaPathak42
 
Laravel overview
Laravel overviewLaravel overview
Laravel overview
Obinna Akunne
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
Prem Sanil
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
tola99
 
Server Side Programming
Server Side ProgrammingServer Side Programming
Server Side Programming
Milan Thapa
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
OECLIB Odisha Electronics Control Library
 

Viewers also liked (17)

Nnnnnn
NnnnnnNnnnnn
Nnnnnn
nautami
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
dimuthu22
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
Madhuri Kavade
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for Beginners
Kevin Hazzard
 
data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.net
subakrish
 
Asp.net
 Asp.net Asp.net
Asp.net
Dinesh kumar
 
Asp.net basic
Asp.net basicAsp.net basic
Asp.net basic
Neelesh Shukla
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
Md. Mahedee Hasan
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
Dr. Awase Khirni Syed
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
Iblesoft
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
Hitesh Santani
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
Guddu gupta
 
ASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsASP.NET 10 - Data Controls
ASP.NET 10 - Data Controls
Randy Connolly
 
Concepts of Asp.Net
Concepts of Asp.NetConcepts of Asp.Net
Concepts of Asp.Net
vidyamittal
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
Madhuri Kavade
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.net
Melick Baranasooriya
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
Kumar S
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
dimuthu22
 
The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for Beginners
Kevin Hazzard
 
data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.net
subakrish
 
C# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENTC# ASP.NET WEB API APPLICATION DEVELOPMENT
C# ASP.NET WEB API APPLICATION DEVELOPMENT
Dr. Awase Khirni Syed
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
Iblesoft
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
Hitesh Santani
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
Guddu gupta
 
ASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsASP.NET 10 - Data Controls
ASP.NET 10 - Data Controls
Randy Connolly
 
Concepts of Asp.Net
Concepts of Asp.NetConcepts of Asp.Net
Concepts of Asp.Net
vidyamittal
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
Kumar S
 
Ad

Similar to ASP.NET Web API and HTTP Fundamentals (20)

11 asp.net web api
11 asp.net web api11 asp.net web api
11 asp.net web api
Michael Mieles Caballero
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
Chalermpon Areepong
 
CodeCamp Iasi 10 March 2012 - Gabriel Enea - ASP.NET Web API
CodeCamp Iasi 10 March 2012 -   Gabriel Enea - ASP.NET Web APICodeCamp Iasi 10 March 2012 -   Gabriel Enea - ASP.NET Web API
CodeCamp Iasi 10 March 2012 - Gabriel Enea - ASP.NET Web API
Codecamp Romania
 
Web Server-Side Programming Techniques
Web Server-Side Programming TechniquesWeb Server-Side Programming Techniques
Web Server-Side Programming Techniques
guest8899ec02
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
Sudheer Satyanarayana
 
Getting Started with API Management
Getting Started with API ManagementGetting Started with API Management
Getting Started with API Management
Revelation Technologies
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009
Cathie101
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009
Cathie101
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
Jean Michel
 
Web api
Web apiWeb api
Web api
udaiappa
 
Spider Course Day 1
Spider Course Day 1Spider Course Day 1
Spider Course Day 1
Harishankaran K
 
Hypertext Transfer Protocol
Hypertext Transfer ProtocolHypertext Transfer Protocol
Hypertext Transfer Protocol
Rajan Pandey
 
SOAP--Simple Object Access Protocol
SOAP--Simple Object Access ProtocolSOAP--Simple Object Access Protocol
SOAP--Simple Object Access Protocol
Masud Rahman
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Introduction server Construction
Introduction server ConstructionIntroduction server Construction
Introduction server Construction
Jisu Park
 
PHP Training: Module 1
PHP Training: Module 1PHP Training: Module 1
PHP Training: Module 1
hussulinux
 
Api 101
Api 101Api 101
Api 101
DrSimoneDiCola
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
Tim Burks
 
ASP.NET Web API Interview Questions By Scholarhat
ASP.NET Web API Interview Questions By ScholarhatASP.NET Web API Interview Questions By Scholarhat
ASP.NET Web API Interview Questions By Scholarhat
Scholarhat
 
Web
WebWeb
Web
Mayank Vora
 
CodeCamp Iasi 10 March 2012 - Gabriel Enea - ASP.NET Web API
CodeCamp Iasi 10 March 2012 -   Gabriel Enea - ASP.NET Web APICodeCamp Iasi 10 March 2012 -   Gabriel Enea - ASP.NET Web API
CodeCamp Iasi 10 March 2012 - Gabriel Enea - ASP.NET Web API
Codecamp Romania
 
Web Server-Side Programming Techniques
Web Server-Side Programming TechniquesWeb Server-Side Programming Techniques
Web Server-Side Programming Techniques
guest8899ec02
 
Building Restful Applications Using Php
Building Restful Applications Using PhpBuilding Restful Applications Using Php
Building Restful Applications Using Php
Sudheer Satyanarayana
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009
Cathie101
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009
Cathie101
 
Hypertext Transfer Protocol
Hypertext Transfer ProtocolHypertext Transfer Protocol
Hypertext Transfer Protocol
Rajan Pandey
 
SOAP--Simple Object Access Protocol
SOAP--Simple Object Access ProtocolSOAP--Simple Object Access Protocol
SOAP--Simple Object Access Protocol
Masud Rahman
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
Tiago Knoch
 
Introduction server Construction
Introduction server ConstructionIntroduction server Construction
Introduction server Construction
Jisu Park
 
PHP Training: Module 1
PHP Training: Module 1PHP Training: Module 1
PHP Training: Module 1
hussulinux
 
Networked APIs with swift
Networked APIs with swiftNetworked APIs with swift
Networked APIs with swift
Tim Burks
 
ASP.NET Web API Interview Questions By Scholarhat
ASP.NET Web API Interview Questions By ScholarhatASP.NET Web API Interview Questions By Scholarhat
ASP.NET Web API Interview Questions By Scholarhat
Scholarhat
 
Ad

More from Ido Flatow (20)

Google Cloud IoT Core
Google Cloud IoT CoreGoogle Cloud IoT Core
Google Cloud IoT Core
Ido Flatow
 
Introduction to HTTP/2
Introduction to HTTP/2Introduction to HTTP/2
Introduction to HTTP/2
Ido Flatow
 
Production Debugging War Stories
Production Debugging War StoriesProduction Debugging War Stories
Production Debugging War Stories
Ido Flatow
 
Introduction to HTTP/2
Introduction to HTTP/2Introduction to HTTP/2
Introduction to HTTP/2
Ido Flatow
 
Production debugging web applications
Production debugging web applicationsProduction debugging web applications
Production debugging web applications
Ido Flatow
 
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
Ido Flatow
 
Building IoT and Big Data Solutions on Azure
Building IoT and Big Data Solutions on AzureBuilding IoT and Big Data Solutions on Azure
Building IoT and Big Data Solutions on Azure
Ido Flatow
 
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the FieldMigrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Ido Flatow
 
The Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with AzureThe Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with Azure
Ido Flatow
 
Introduction to HTTP/2
Introduction to HTTP/2Introduction to HTTP/2
Introduction to HTTP/2
Ido Flatow
 
Debugging your Way through .NET with Visual Studio 2015
Debugging your Way through .NET with Visual Studio 2015Debugging your Way through .NET with Visual Studio 2015
Debugging your Way through .NET with Visual Studio 2015
Ido Flatow
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
Ido Flatow
 
Debugging the Web with Fiddler
Debugging the Web with FiddlerDebugging the Web with Fiddler
Debugging the Web with Fiddler
Ido Flatow
 
EF Core (RC2)
EF Core (RC2)EF Core (RC2)
EF Core (RC2)
Ido Flatow
 
Introducing HTTP/2
Introducing HTTP/2Introducing HTTP/2
Introducing HTTP/2
Ido Flatow
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
Powershell For Developers
Powershell For DevelopersPowershell For Developers
Powershell For Developers
Ido Flatow
 
IaaS vs. PaaS: Windows Azure Compute Solutions
IaaS vs. PaaS: Windows Azure Compute SolutionsIaaS vs. PaaS: Windows Azure Compute Solutions
IaaS vs. PaaS: Windows Azure Compute Solutions
Ido Flatow
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF Workshop
Ido Flatow
 
What's New in WCF 4.5
What's New in WCF 4.5What's New in WCF 4.5
What's New in WCF 4.5
Ido Flatow
 
Google Cloud IoT Core
Google Cloud IoT CoreGoogle Cloud IoT Core
Google Cloud IoT Core
Ido Flatow
 
Introduction to HTTP/2
Introduction to HTTP/2Introduction to HTTP/2
Introduction to HTTP/2
Ido Flatow
 
Production Debugging War Stories
Production Debugging War StoriesProduction Debugging War Stories
Production Debugging War Stories
Ido Flatow
 
Introduction to HTTP/2
Introduction to HTTP/2Introduction to HTTP/2
Introduction to HTTP/2
Ido Flatow
 
Production debugging web applications
Production debugging web applicationsProduction debugging web applications
Production debugging web applications
Ido Flatow
 
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
From VMs to Containers: Introducing Docker Containers for Linux and Windows S...
Ido Flatow
 
Building IoT and Big Data Solutions on Azure
Building IoT and Big Data Solutions on AzureBuilding IoT and Big Data Solutions on Azure
Building IoT and Big Data Solutions on Azure
Ido Flatow
 
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the FieldMigrating Customers to Microsoft Azure: Lessons Learned From the Field
Migrating Customers to Microsoft Azure: Lessons Learned From the Field
Ido Flatow
 
The Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with AzureThe Essentials of Building Cloud-Based Web Apps with Azure
The Essentials of Building Cloud-Based Web Apps with Azure
Ido Flatow
 
Introduction to HTTP/2
Introduction to HTTP/2Introduction to HTTP/2
Introduction to HTTP/2
Ido Flatow
 
Debugging your Way through .NET with Visual Studio 2015
Debugging your Way through .NET with Visual Studio 2015Debugging your Way through .NET with Visual Studio 2015
Debugging your Way through .NET with Visual Studio 2015
Ido Flatow
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
Ido Flatow
 
Debugging the Web with Fiddler
Debugging the Web with FiddlerDebugging the Web with Fiddler
Debugging the Web with Fiddler
Ido Flatow
 
Introducing HTTP/2
Introducing HTTP/2Introducing HTTP/2
Introducing HTTP/2
Ido Flatow
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
Powershell For Developers
Powershell For DevelopersPowershell For Developers
Powershell For Developers
Ido Flatow
 
IaaS vs. PaaS: Windows Azure Compute Solutions
IaaS vs. PaaS: Windows Azure Compute SolutionsIaaS vs. PaaS: Windows Azure Compute Solutions
IaaS vs. PaaS: Windows Azure Compute Solutions
Ido Flatow
 
Advanced WCF Workshop
Advanced WCF WorkshopAdvanced WCF Workshop
Advanced WCF Workshop
Ido Flatow
 
What's New in WCF 4.5
What's New in WCF 4.5What's New in WCF 4.5
What's New in WCF 4.5
Ido Flatow
 

Recently uploaded (20)

Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko"Rebranding for Growth", Anna Velykoivanenko
"Rebranding for Growth", Anna Velykoivanenko
Fwdays
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Rock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning JourneyRock, Paper, Scissors: An Apex Map Learning Journey
Rock, Paper, Scissors: An Apex Map Learning Journey
Lynda Kane
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Automation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From AnywhereAutomation Dreamin': Capture User Feedback From Anywhere
Automation Dreamin': Capture User Feedback From Anywhere
Lynda Kane
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 

ASP.NET Web API and HTTP Fundamentals

  • 1. ASP.NET Web API and HTTP Fundamentals Ido Flatow Senior Architect Microsoft MVP SELA Group @idoFLATOW http://bit.ly/flatow-blog This presentation: http://sdrv.ms/1eKAsRd
  • 2. ASP.NET WEB API AND HTTP FUNDAMENTALS CRAMMING YOUR BRAINS WITH HTTP & ASP.NET WEB API  HTTP Fundamentals via Web API  Hosting  HTTP Messages  HTTP.SYS  URIs  IIS 101  Routing  HTTP compression  Verbs  Persisted Connections  Controllers and Actions  Web API Self Hosting  Status Codes  HttpRequestMessage HttpResponseMessage  Error Handling  Content Negotiation  Media Type Formatters  OData  Validations  Dependency Resolver www.devconnections.com  More HTTP and Web API  Caching  Concurrency  Security  Streaming  WebSockets & SignalR 2
  • 3. ASP.NET WEB API AND HTTP FUNDAMENTALS ABOUT ME   Senior architect, Sela Group Co-author of:     WCF 4 – Microsoft official course   Developing Windows Azure and Web Services – Microsoft official course Pro .NET Performance – Apress Microsoft MVP Focus on server, services, and cloud technologies Manager of the Israeli Web Developers User Group www.devconnections.com
  • 4. ASP.NET WEB API AND HTTP FUNDAMENTALS WHY IS HTTP IMPORTANT?  HTTP is a first class application layer protocol  Unlike other protocols it was created to support a single information system  That system happened to be the largest and main information system of the human race: www.devconnections.com 4
  • 5. ASP.NET WEB API AND HTTP FUNDAMENTALS NO REALLY, WHY?  Today's   systems face new challenges: Internet scale applications Cloud-based applications www.devconnections.com 5
  • 6. ASP.NET WEB API AND HTTP FUNDAMENTALS NO REALLY, WHY?  Today's  systems face new challenges: Broader reach of clients www.devconnections.com 6
  • 7. ASP.NET WEB API AND HTTP FUNDAMENTALS WHAT ABOUT ASP.NET WEB API?  The .NET platform never had a first class framework for HTTP-based services  WCF was created as a SOAP-based framework and never really matured to support HTTP www.devconnections.com 7
  • 8. ASP.NET WEB API AND HTTP FUNDAMENTALS THE HISTORY OF ASP.NET WEB API 6 Preview Versions WCF Web API on CodePlex WCF WebHttp Binding (.NET 4) www.devconnections.com ASP.NET Web API 4 Release ASP.NET is Open Source ASP.NET Web API 2 Release Candidate ASP.NET Web API (Beta) 8
  • 9. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP MESSAGES 101  HTTP is a first class application protocol:  Widely supported across platforms and devices  Scalable  Simple  Uses the request-response messaging pattern  Define resource-based semantics and not RPC (Remote Procedure Call) or methods www.devconnections.com 9
  • 10. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP REQUEST MESSAGES GET http://localhost:2300/api/agents/Bond HTTP/1.1 Accept: text/html, application/xhtml+xml, */* Accept-Language: en-US,en;q=0.7,he;q=0.3 User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0) Accept-Encoding: gzip, deflate Host: localhost:2300 DNT: 1 Connection: Keep-Alive www.devconnections.com 10
  • 11. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP RESPONSE MESSAGES HTTP/1.1 200 OK Cache-Control: public, max-age=300 Content-Type: application/json; charset=utf-8 ETag: "1" Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 Date: Mon, 19 Nov 2012 17:49:40 GMT Content-Length: 142 { } "Id": "Bond", "FullName": "James Bond", "Alias": "007", "Version": 1, "Image": "http://localhost:2300/api/agents/Bond.jpg" www.devconnections.com 11
  • 12. ASP.NET WEB API AND HTTP FUNDAMENTALS URIS  HTTP is not an RPC protocol  HTTP uses URIs to identify resources over the network  An HTTP URI has the following basic structure: http://theagency.com:8080/agents?id=1 Schema www.devconnections.com Host Port Absolute Path Query 12
  • 13. ASP.NET WEB API AND HTTP FUNDAMENTALS CLEAN URLS AND ASP.NET  Using clean URLs can be a problem with IIS  IIS needs extensions to map requests to handlers  Without extensions, IIS is lost  ASP.NET Routing to the rescue with UrlRoutingModule  It’s all about patterns… and mapping them to handlers  The starting point of MVC, Dynamic Data, and Web API  System.Web.Routing.RouteTable.Routes.MapHttpRoute RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); www.devconnections.com 13
  • 14. ASP.NET WEB API AND HTTP FUNDAMENTALS THE BASICS OF WEB API - ROUTING DEMO www.devconnections.com 14
  • 15. ASP.NET WEB API AND HTTP FUNDAMENTALS ROUTING WITH ATTRIBUTES  Why attributes over convention?  Child (sub) resources  Multiple type of parameters or return values  Versioning of actions and controllers  Start  by enabling attribute routing config.MapHttpAttributeRoutes(); [RoutePrefix("api/agents/{agentId}")] public class ObservationsController : ApiController { // GET api/agents/bond/observations [HttpGet("observations/{date}")] public Observation Get(string agentId, DateTime date) { ... } } www.devconnections.com 15
  • 16. ASP.NET WEB API AND HTTP FUNDAMENTALS VERBS  HTTP defines a set of Methods or Verbs that add an action-like semantics to requests  Verbs are defined as the first segment of the request-line: GET http://localhost:4392/travelers/1 HTTP/1.1  There are eight verbs defined in HTTP 1.1: GET POST PUT DELETE www.devconnections.com HEAD OPTIONS TRACE CONNECT 16
  • 17. ASP.NET WEB API AND HTTP FUNDAMENTALS 3, 2, 1, ACTIONS!  Actions are matched by HTTP verb public names and the existence of parameters class ProductsController : ApiController { public IEnumerable<Product> GetProducts() {...} public Product GetProductById(int id) {...} public HttpResponseMessage PostProduct(Product product) {...} } GET api/products GET api/products/42 POST api/products www.devconnections.com DELETE api/products/42
  • 18. ASP.NET WEB API AND HTTP FUNDAMENTALS HANDLING VERBS IN ASP.NET WEB API DEMO www.devconnections.com 18
  • 19. ASP.NET WEB API AND HTTP FUNDAMENTALS STATUS CODES  Status codes describe the result of the server’s effort to satisfy the request  Passed in the response's status-line as three digit alongside a textual description called reason phrase  HTTP has five different categories of status-codes:  1xx – Informational (100 / 101)  2xx – Success (200 – 206)  3xx – Redirection (300 – 307)  4xx – Client Error (400 – 417)  5xx – Server Error (500 – 505) www.devconnections.com 19
  • 20. ASP.NET WEB API AND HTTP FUNDAMENTALS STATUS CODE EXAMPLES  404?  401?  304?  503?  500?  200?  301?  302? www.devconnections.com 20
  • 21. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP RESPONSE MESSAGE  Returning an HttpResponseMessage allows more control over the response, including:  Status code  HTTP headers  Entity body public HttpResponseMessage CreateAgent(Agent agent) { agent = _repository.Add(agent); var response = Request.CreateResponse<Agent>(HttpStatusCode.Created, agent); response.Headers.Location = GetAgentLocation(agent.Id); return response; } www.devconnections.com 21
  • 22. ASP.NET WEB API AND HTTP FUNDAMENTALS HANDLING STATUS CODES DEMO www.devconnections.com 22
  • 23. ASP.NET WEB API AND HTTP FUNDAMENTALS ERROR HANDLING  In HTTP services errors are handled by    Returning an appropriate status code Returning an entity body explaining the error (when applicable) Web API allows you to handle exceptions by  Return an HttpResponseMessage with appropriate status code (404, 500 …)  Throw an HttpResponseException  Create a general exception handler by using Filters www.devconnections.com 23
  • 24. ASP.NET WEB API AND HTTP FUNDAMENTALS HANDLING ERRORS DEMO www.devconnections.com 24
  • 25. ASP.NET WEB API AND HTTP FUNDAMENTALS MEDIA TYPES  HTTP was originally designed to transfer Hypertext  Hypertext documents contain references to other resources including images, video, etc.  Multipurpose Internet Mail Extensions (MIME) Types or Media-types allow HTTP to express different formats: text/html; charset=UTF-8 Type www.devconnections.com Subtype Type specific parameters 25
  • 26. ASP.NET WEB API AND HTTP FUNDAMENTALS CONTENT NEGOTIATION  HTTP defines a process to best match the server’s response to the client’s expectation  Negotiation can be done using:  Headers: Accept, Accept- Language, Accept- Charset, Accept-Encoding  URI: File extensions (.jpeg, .html), host-name: (com, org), path and query www.devconnections.com 26
  • 27. ASP.NET WEB API AND HTTP FUNDAMENTALS MEDIA TYPE FORMATTERS  ASP.NET Web API uses Media Type Formatters to control serialization  Each media type formatter is associated with a media type, file extension, or query string  The host is configured with a collection of MediaTypeFormatter objects  Create custom formatters by deriving from:  MediaTypeFormatter – asynchronous read/write  BufferedMediaTypeFormatter – synchronous read/write www.devconnections.com 27
  • 28. ASP.NET WEB API AND HTTP FUNDAMENTALS CONTENT NEGOTIATION IN WEB API DEMO www.devconnections.com 28
  • 29. ASP.NET WEB API AND HTTP FUNDAMENTALS VALIDATING USER INPUT  Use System.ComponentModel.DataAnnotations on entity classes to add validation rules  Validation rules can be check by calling ModelState.IsValid  When validation fails, return a Bad Request (400)  ModelState is a dictionary of property name & errors, use it to construct a meaningful response www.devconnections.com 29
  • 30. ASP.NET WEB API AND HTTP FUNDAMENTALS VALIDATING USER INPUT public class Contact { [Required] public string FullName { get; set;} [Email] public string Email { get; set;} } if (!this.ModelState.IsValid) { var errors = this.ModelState.Where(s => s.Value.Errors.Count > 0) .Select(s => new KeyValuePair<string, string> (s.Key, s.Value.Errors.First().ErrorMessage)); response = Request.CreateResponse( HttpStatusCode.BadRequest, errors); } www.devconnections.com 30
  • 31. ASP.NET WEB API AND HTTP FUNDAMENTALS VALIDATING USER INPUT DEMO www.devconnections.com 31
  • 32. ASP.NET WEB API AND HTTP FUNDAMENTALS ODATA QUERYABLE ACTIONS  The Open Data Protocol (OData) provides a RESTful standard for exposing data models  OData uses URIs to perform query operations:  Entity projection – $select, $expand  Sorting – $orderby  Entity sub-setting – $top, $skip  Filtering – $filter, logical operators: eq, ne, gt, lt www.devconnections.com 32
  • 33. ASP.NET WEB API AND HTTP FUNDAMENTALS DEFINING ODATA ACTIONS  Install the Microsoft.AspNet.WebApi.OData NuGet package  Define an action with the following characteristics:  Returns IQueryable<T> or IEnumerable<T>  Decorated with the [Queryable] attribute [Queryable] public IQueryable<Agent> GetAgents() { } www.devconnections.com 33
  • 34. ASP.NET WEB API AND HTTP FUNDAMENTALS WEB API AND ODATA [Queryable] public IQueryable<Agent> GetAgents() { return repository.GetAll().AsQueryable(); } api/agents?$orderby=Name api/agents?$skip=10 api/agents?$skip=50&$top=10 api/agents?$filter=salary gt 50000 www.devconnections.com
  • 35. ASP.NET WEB API AND HTTP FUNDAMENTALS ODATA ACTIONS DEMO www.devconnections.com 35
  • 36. ASP.NET WEB API AND HTTP FUNDAMENTALS ODATA MODELS  OData also provides a mechanism for exposing entity models:  Publishing the models metadata  Exposing relations between entities using the Atom media-type www.devconnections.com 36
  • 37. ASP.NET WEB API AND HTTP FUNDAMENTALS CREATING AND EXPOSING ODATA MODELS  Exposing an OData model requires the following configuration:  Creating an EDM model using the ODataConventionModelBuilder class  Adding a route using the MapODataRoute method  In addition, any controller exposed in the model should derive from the ODataController or EntitySetController<TEntity, TKey> classes www.devconnections.com 37
  • 38. ASP.NET WEB API AND HTTP FUNDAMENTALS CONSUMING ODATA SERVICES  Add a service reference to the OData service  Create a new instance of the generated Container class  Use LINQ to query the container var client = new MyODataService.Container(new Uri("…")); var agent = (from a in client.Agents where a.Id == "Bond" select a).Single(); www.devconnections.com 38
  • 39. ASP.NET WEB API AND HTTP FUNDAMENTALS ODATA MODELS DEMO www.devconnections.com 39
  • 40. ASP.NET WEB API AND HTTP FUNDAMENTALS DEPENDENCY RESOLVER AND THE API CONTROLLER  To be testable, the ApiController should support dependency injection  Web API supports dependency injection with the IDependencyResolver interface  Implement your custom resolver or use it to wrap a known IoC Container (Castle, Unity, MEF, Ninject…)  Register the dependency resolver through Web API global configuration  And Voilà! www.devconnections.com 40 40
  • 41. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP.SYS, WHAT’S THAT?  It’s the thing that handles HTTP on your machine  It’s a kernel mode device driver  Ever since Windows XP SP2 / Windows Server 2003  Responsible of   Kernel mode SSL (full support as of Windows Server 2008)  Caching responses in kernel mode   Routing requests to the correct application Implementing QoS, such as connection limits and timeouts Want to know more? netsh http show www.devconnections.com 41
  • 42. ASP.NET WEB API AND HTTP FUNDAMENTALS IIS 101   Web application hosting Comes in two flavors    IIS Express Full IIS (or simply IIS) Provides  Reliability  Manageability  Security  Performance  Scalability www.devconnections.com 42
  • 43. ASP.NET WEB API AND HTTP FUNDAMENTALS ENABLING COMPRESSION WITH IIS   Compression is something the client needs to request Requests are not normally compressed  Accept-Encoding: gzip,deflate Server is not obligated to compress the response  Content-Encoding: gzip / deflate  IIS Compression Modes Dynamic Compression Static Compression www.devconnections.com Scenarios Considerations Small number of requests Uses CPU and memory Limited network bandwidth Not cached Improve transmission times Can be cached Graphic-heavy sites Uses some CPU 43
  • 44. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP PERSISTENT CONNECTION IT’S ALIVE   Beginning with HTTP 1.1, clients and servers must support persistent connections Persistent is good   Fewer TCP connections = less congestion   Single connection can pipeline HTTP requests   Less simultaneous opened connections = less CPU No re-handshaking = reduced latency Send Connection: Keep-Alive in request and response headers to keep the underlying TCP connection open Connection is dropped if either end lacks sending the Keep-Alive header – Implementation Dependent www.devconnections.com 44
  • 45. ASP.NET WEB API AND HTTP FUNDAMENTALS KEEPING IT ALIVE! DEMO www.devconnections.com 45
  • 46. ASP.NET WEB API AND HTTP FUNDAMENTALS KEEP IT ALIVE, BUT FOR HOW LONG?      IIS by default adds Keep-Alive to every response HTTP.SYS has a default timeout of 120 seconds for idle connections When expecting many clients with a small number of request, Keep-Alive may have an overhead For short visits, consider disabling Keep-Alive or reduce the idle timeout to a couple of seconds (5? 2? 1?) Use logs to check visits and frequency of idle connections:  IIS log files: C:inetpublogsLogFiles  HTTP.SYS log files: %windir%system32LogFilesHTTPERR www.devconnections.com 46
  • 47. ASP.NET WEB API AND HTTP FUNDAMENTALS WHO NEEDS IIS? WE HAVE SELF-HOSTING IIS is the natural hosting environment for the ASP.NET web stack, Web API included  When IIS is not an option or unwanted, use a self-hosted Web API  Just follow three basic steps:    Create host configuration and routing rules   Install the Microsoft ASP.NET Web API Self Host NuGet package Start the self-hosted server Under the covers, Web API self-hosting is handled by WCF www.devconnections.com 47
  • 48. ASP.NET WEB API AND HTTP FUNDAMENTALS CACHING  HTTP caches store copies of responses to reduce network traffic  HTTP caches reduces call latency and increases server throughput  Caches are a main factor for scalability on the web www.devconnections.com 48
  • 49. ASP.NET WEB API AND HTTP FUNDAMENTALS TYPES OF CACHES  Browser/Client Cache Stores representations locally on the computer’s hard drive  Proxy Cache Corporates and ISPs provide shared proxies providing shared cache on their network  Gateway (Reverse Proxy) Cache Stores representations on behalf of the server. Content Delivery Networks (CDNs) use gateway cache distributed around the web www.devconnections.com 49
  • 50. ASP.NET WEB API AND HTTP FUNDAMENTALS CONTROLLING CACHE  HTTP headers can be used to control cache behaviors  HTTP provides method the avoid staleness of cached data  Expiration  Validation  Invalidation www.devconnections.com 50
  • 51. ASP.NET WEB API AND HTTP FUNDAMENTALS CONTROLLING CACHE DEMO www.devconnections.com 51
  • 52. ASP.NET WEB API AND HTTP FUNDAMENTALS ETAG: VERSIONING & CONCURRENCY     When caching content, we need to identify when content has changed The ETag (entity tag) header represents the version of the content ETags are sent to the client with the response, and are re-sent to the server on subsequent requests In the action, compare received and existing ETags, and return either:    A new entity if they are different An HTTP 304 (Not Modified) if they are identical When updating entities using POST/PUT, use the ETag for concurrency (version) checks www.devconnections.com
  • 53. ASP.NET WEB API AND HTTP FUNDAMENTALS ETAG VERSIONING public HttpResponseMessage Get(int id) { HttpResponseMessage response; var etag = Request.Headers.IfNoneMatch.FirstOrDefault(); Agent agent = _manager.GetAgentById(id); if (etag != null && etag.ToString().Replace(@"""", "") == agent.Version) { response = new HttpResponseMessage(HttpStatusCode.NotModified); } else { response = Request.CreateResponse(HttpStatusCode.OK, agent); response.Headers.ETag = new EntityTagHeaderValue( string.Format(@"""{0}""", agent.Version)); } return response; www.devconnections.com 53 }
  • 54. ASP.NET WEB API AND HTTP FUNDAMENTALS SECURITY  HTTP messages are clear text, in order to have any form of secured connection they must be encrypted  This is what SSL is for  Once encrypted there are still several challenges remaining:  Authentication  Persisting authentication throughout the conversation  Authorization www.devconnections.com 54
  • 55. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTPS - HOW SECURE SOCKETS LAYER WORKS 3. Client verifies certificate’s authenticity 1. Client requests a secured session 2. Server responds with an X.509 certificate 4. Client sends a symmetric encryption key (encrypted with the server’s public key) 6. Client and server exchange encrypted messages (encrypted with the symmetric key) 5. Server decrypts the encryption key with its private key www.devconnections.com
  • 56. ASP.NET WEB API AND HTTP FUNDAMENTALS CLASSIC HTTP AUTHENTICATION  HTTP uses the Authorization header to pass authentication data: Authorization: Basic eWFuaXY6eWFuaXY=  According to specs, HTTP supports only two schemas:    Basic (plain text) Digest (hashed password) Nowadays, it is common to find other schemas:  NTLM / Negotiate (Windows authentication)  Certificate  OAuth www.devconnections.com 56
  • 57. ASP.NET WEB API AND HTTP FUNDAMENTALS BASIC AUTHENTICATION DEMO www.devconnections.com 57
  • 58. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP STREAMING  Advantages   Message can be handled before received completely   Less large memory allocation and buffering Connection can remain opened for a long time Useful for    File download/upload Live data feed (notifications, video streams, …) It’s a chunking mechanism  Uses a persistent HTTP connection  The Content-Length HTTP header is omitted  Each chunk is sent as size + chunk  Chunk size can vary  Stream ends when last chunk is sent with size 0 (zero) www.devconnections.com 58
  • 59. ASP.NET WEB API AND HTTP FUNDAMENTALS HTTP STREAMING AND WEB API  Reading a streamed request    Request.Content.ReadAsStreamAsync (File Stream ) Request.Content.ReadAsMultipartAsync (Multi-part Stream) Writing a streamed response  Do you want to pull from an existing stream? Or push your own data down the stream?  Pull : StreamContent(inputStream)  Push: PushStreamContent(contentWritingAction)  When pushing data use Stream.Flush() to chunk www.devconnections.com 59
  • 60. ASP.NET WEB API AND HTTP FUNDAMENTALS STREAMING WITH WEB API DEMO www.devconnections.com 60
  • 61. ASP.NET WEB API AND HTTP FUNDAMENTALS DUPLEX COMMUNICATION WITH HTTP  HTTP is a request-response protocol  Updates are through server polling    Periodic polling (Anything new?) Long polling (I’m waiting for you!) Many disadvantages  Periodic polling inflicts high-latency on updates  Long polling is hard to implement  Can cause bandwidth overhead if used improperly www.devconnections.com 61
  • 62. ASP.NET WEB API AND HTTP FUNDAMENTALS WEBSOCKETS IN A GLANCE  Bi-directional  Supports both HTTP and HTTPS (SSL)  Accessible  Supports TCP channel (full-duplex) through JavaScript API cross-domain calls  Client-side - IE10, Chrome, Firefox, .NET 4.5  Server-side – IIS 8, ASP.NET 4.5, SignalR  Standardization www.devconnections.com is still in progress!!
  • 63. ASP.NET WEB API AND HTTP FUNDAMENTALS ASP.NET SIGNALR 101  Real-time, over HTTP persistent connection abstraction  Useful for dashboards & monitoring, collaborative work, job progress, gaming…  SignalR works everywhere  WebSockets  Server Sent Events  Forever Frame  Long Polling www.devconnections.com 63
  • 64. ASP.NET WEB API AND HTTP FUNDAMENTALS ASP.NET SIGNALR 101  Supported clients:  Desktop applications using .NET 4/4.5  Web browsers using JavaScript  Windows Store and Windows Phone Apps  Supports scaling servers to Web farm with Windows Azure Service Bus, Redis, and SQL Server www.devconnections.com 64
  • 65. ASP.NET WEB API AND HTTP FUNDAMENTALS SIGNALR API, CHOOSE WHAT WORKS FOR YOU  Connections  Low level  Raw strings up and down (the “old way”)  Broadcast to all clients, groups, or individuals  Connect, reconnect & disconnect semantics  Hubs  Built on top of connections  Client-Server and Server-Client RPC  Automatic client proxy generation for JavaScript www.devconnections.com 65
  • 66. ASP.NET WEB API AND HTTP FUNDAMENTALS ASP.NET SIGNALR DEMO www.devconnections.com 66
  • 67. ASP.NET WEB API AND HTTP FUNDAMENTALS SO WHAT DID WE LEARN TODAY?  HTTP Fundamentals via Web API  Hosting You are now an HTTP ninja Rank 1. Just 4 more ranks to go!!  HTTP Messages  HTTP.SYS  URIs  IIS 101  Routing  HTTP compression  Verbs  Persisted Connections  Controllers and Actions  Web API Self Hosting  Status Codes  HttpRequestMessage HttpResponseMessage  Error Handling  Content Negotiation  Media Type Formatters  OData  Validations  Dependency Resolver www.devconnections.com  More HTTP and Web API  Caching  Concurrency  Security  Streaming  WebSockets & SignalR 67
  • 68. ASP.NET WEB API AND HTTP FUNDAMENTALS RESOURCES  HTTP   www.ietf.org/rfc/rfc2616.txt REST   www.ics.uci.edu/~fielding/pubs/dissertation/top.htm ASP.NET Web API  www.asp.net/web-api  www.asp.net/web-api/videos   This Presentation: sdrv.ms/1eKAsRd webapibloggers.com (without www) Fiddler  www.fiddler2.com  www.youtube.com/watch?v=7Tw5EHvTERc  “Debugging the Web with Fiddler”, Tuesday 2:00PM www.devconnections.com 68

Editor's Notes

  • #16: Additionally supports constraints (type, min/max restriction, regex, and range), optional and default values, ordering, and extensibility.http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
  • #52: Controlling Cache Behavior