The document provides an overview of a presentation on ASP.NET Web API and HTTP fundamentals. It includes sections on HTTP messages and URIs, routing and verbs in Web API, status codes, error handling, content negotiation, media type formatters, validating user input, and enabling OData queryable actions. The presentation aims to cover HTTP fundamentals through the lens of Web API, cramming attendees' brains with information on how to build HTTP-based web services using ASP.NET Web API.
Presented by eZ's Bertrand Dunogier and Andrew Longosz.
The time for monolithic applications is far gone. Now developers are building solutions by assembling applications and services of all kinds and in all ways. In this session we’ll focus on how eZ Platform embraces the modern way of building applications—from interacting its content repository service via the remote API, to integrating third-party services simply within eZ.
Presented by eZ's Bertrand Dunogier and Andrew Longosz.
The time for monolithic applications is far gone. Now developers are building solutions by assembling applications and services of all kinds and in all ways. In this session we’ll focus on how eZ Platform embraces the modern way of building applications—from interacting its content repository service via the remote API, to integrating third-party services simply within eZ.
Architecting the Future: Abstractions and Metadata - KCDCDaniel Barker
Kubernetes and Docker are two of the top open source projects, and they’re built around abstractions and metadata. These two concepts are the key to architecting in the future. Come with me as I dig a little deeper into these concepts within k8s and Docker and provide some examples from my own work.
Browser Serving Your We Application Security - ZendCon 2017Philippe Gamache
One important concept in web application security is defense in depth. You protect your server, your network, your database, and your application, but what about the user browser? Can it be done?
Yes! Several new technologies and protocols to assist security has been added to the browsers. Several should be added, activated, and configured from your web server or webpage. In this session we'll explore these technologies and learn how to use them. You’ll learn about the Robots meta tags (for crawlers indexing), browsing compatibility, XSS and clickjacking protection, SSL/TLS Control, and content security policy.
Web Server Technologies I: HTTP & Getting StartedPort80 Software
Introduction to HTTP: TCP/IP and application layer protocols, URLs, resources and MIME Types, HTTP request/response cycle and proxies. Setup and deployment: Planning Web server & site deployments, Site structure and basic server configuration, Managing users and hosts.
Setting up the Red5 environment, building sample applications and integrating with flash. We will look at how Red5 works within the flash IDE and build a sample chat application, video streaming, and multi-user environment.
APIs are must nowadays. We'll see how API Platform can help us bringing functional api platforms into production quickly. We will identify the key concepts of the framework, we will understand how to instruct it according to our needs and how it naturally integrates into the Symfony ecosystem.
Hybrid Mobile App Development | Hire Application Developers | Application Dev...MetaDesign solutions
Hybrid Mobile App Development with hiring efficient Application Developers from MetaDesign Solutions is an ISO (9001:2008) certified software development company.
Architecting the Future: Abstractions and Metadata - KCDCDaniel Barker
Kubernetes and Docker are two of the top open source projects, and they’re built around abstractions and metadata. These two concepts are the key to architecting in the future. Come with me as I dig a little deeper into these concepts within k8s and Docker and provide some examples from my own work.
Browser Serving Your We Application Security - ZendCon 2017Philippe Gamache
One important concept in web application security is defense in depth. You protect your server, your network, your database, and your application, but what about the user browser? Can it be done?
Yes! Several new technologies and protocols to assist security has been added to the browsers. Several should be added, activated, and configured from your web server or webpage. In this session we'll explore these technologies and learn how to use them. You’ll learn about the Robots meta tags (for crawlers indexing), browsing compatibility, XSS and clickjacking protection, SSL/TLS Control, and content security policy.
Web Server Technologies I: HTTP & Getting StartedPort80 Software
Introduction to HTTP: TCP/IP and application layer protocols, URLs, resources and MIME Types, HTTP request/response cycle and proxies. Setup and deployment: Planning Web server & site deployments, Site structure and basic server configuration, Managing users and hosts.
Setting up the Red5 environment, building sample applications and integrating with flash. We will look at how Red5 works within the flash IDE and build a sample chat application, video streaming, and multi-user environment.
APIs are must nowadays. We'll see how API Platform can help us bringing functional api platforms into production quickly. We will identify the key concepts of the framework, we will understand how to instruct it according to our needs and how it naturally integrates into the Symfony ecosystem.
Hybrid Mobile App Development | Hire Application Developers | Application Dev...MetaDesign solutions
Hybrid Mobile App Development with hiring efficient Application Developers from MetaDesign Solutions is an ISO (9001:2008) certified software development company.
ASP.NET Web API is the de facto framework for building HTTP-based services in the .NET ecosystem. With its WCF and MVC lineage, Web API brings to the table better architecture, easier configuration, increased testability, and as always, it's customizable from top to bottom. But to properly use Web API it is not enough to get familiar with its architecture and API, you also need to really understand what HTTP is all about. HTTP is the most common application layer protocol in the world, and yet, not many web developers are familiar with HTTP concepts such as of chunking, caching, and persisted connections. In this full-day tutorial, we will focus on designing and implementing HTTP-based services with ASP.NET Web API, and you will learn how to better use it to implement the features provided by HTTP.
Topics Covered
==============================
Overview of .NET
Overview of ASP.NET
Creating an ASP.NET Web Form
Adding Event Procedures
Validating User Input
Push notifications, in-app messaging, mobile message centers: get the inside scoop on what to say, how to say it and how to coordinate all of your mobile messaging in this presentation from two of Urban Airship's top mobile marketing experts.
Designing and building RESTful APIs isn’t easy. On its surface, it may seem simple – after all, we’re only marshaling JSON back and forth over HTTP right? However, that’s only a small part of the equation. There are many things to keep in mind while building the systems that act as the key to your system.
In this session, we’ll delve into several best practices to keep in mind when designing your RESTful API. We’ll discuss authentication, versioning, controller/model design, and testability. We’ll also explore the do’s and don’t’s of RESTful API management so that you make sure your APIs are simple, consistent, and easy-to-use. Finally, we’ll discuss the importance of documentation and change management. The session will show examples using ASP.NET Web API and C#. However, this session will benefit anyone who is or might be working on a RESTful API.
APIs are one of the main elements of cloud services. All major cloud service providers expose REST APIs to allow you to programmatically access their services and capabilities. SOAP and REST are the two most common ways of exposing APIs, whether to external, partner, cloud, or internal developers.
The concept of API management is to publish these web APIs for consumption, and includes capabilities such as monitoring, security, and documentation.
This presentation introduces basic concepts of APIs, API management, cloud REST services, and a brief walkthrough of WSO2 API Manager and the Oracle API Gateway to see how you can centrally publish, expose, and secure APIs, essentially virtualizing your backend services.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
The slides provide a major overview on SOAP protocol, and demonstrates a working example that uses SOAP for RPC. It uses WCF/visual studio and Apache Axis for the implementation.
Web API or WCF - An Architectural ComparisonAdnan Masood
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. The new ASP.NET Web API is a continuation of the previous WCF Web API projection. WCF was originally created to enable SOAP-based services and other related bindings. However, for simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API is a good choice.
In this meeting we discussed what do you need to understand as an architect to implement your service oriented architecture using WCF or ASP.NET web API. With code samples, we will elaborate on WCF Web API’s transition to ASP.NET Web API and respective constructs such as Service vs. Web API controller, Operation vs. Action, URI templates vs ASP.NET Routing, Message handlers, Formatters and Operation handlers vs Filters, model binders. WebApi offers support for modern HTTP programming model with full support for ASP.NET Routing, content negotiation and custom formatters, model binding and validation, filters, query composition, is easy to unit test and offers improved Inversion of Control (IoC) via DependencyResolver.
You will walk away with a sample set of services that run on Silverlight, Windows Forms, WPF, Windows Phone and ASP.NET.
1. Ido Flatow
Senior Architect
Microsoft MVP
SELA Group
ASP.NET Web API
and HTTP Fundamentals
@idoFLATOW
http://bit.ly/flatow-blog
This presentation:
http://sdrv.ms/1eKAsRd
http://www.asp.net/web-
api/overview/getting-started-with-
aspnet-web-api/tutorial-your-first-web-
api
2. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
CRAMMING YOUR BRAINS WITH
HTTP & ASP.NET WEB API
HTTP Fundamentals via Web API
HTTP Messages
URIs
Routing
Verbs
Controllers and Actions
Status Codes
HttpRequestMessage
HttpResponseMessage
Error Handling
Content Negotiation
Media Type Formatters
OData
Validations
Dependency Resolver
Hosting
HTTP.SYS
IIS 101
HTTP compression
Persisted Connections
Web API Self Hosting
More HTTP and Web API
Caching
Concurrency
Security
Streaming
WebSockets & SignalR
2
3. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
ABOUT ME
Senior architect, Sela Group
Co-author of:
Developing Windows Azure and Web Services –
Microsoft official course
WCF 4 – Microsoft official course
Pro .NET Performance – Apress
Microsoft MVP
Focus on server, services, and cloud
technologies
Manager of the Israeli Web Developers User
Group
4. 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:
4
5. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
NO REALLY, WHY?
Today's systems face new challenges:
Internet scale applications
Cloud-based applications
5
7. www.devconnections.com
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
7
8. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
THE HISTORY OF ASP.NET WEB API
8
ASP.NET is
Open Source
ASP.NET Web API
(Beta)
WCF Web API
on CodePlex
6 Preview Versions
WCF WebHttp
Binding (.NET 4)
ASP.NET Web API 4
Release
ASP.NET Web API 2
Release Candidate
9. www.devconnections.com
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
9
10. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
HTTP REQUEST MESSAGES
10
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
11. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
HTTP RESPONSE MESSAGES
11
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"
}
12. www.devconnections.com
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:
12
Schema Host Port Absolute
Path
Query
http://theagency.com:8080/agents?id=1
13. www.devconnections.com
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
13
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
15. www.devconnections.com
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();
15
[RoutePrefix("api/agents/{agentId}")]
public class ObservationsController : ApiController
{
// GET api/agents/bond/observations
[HttpGet("observations/{date}")]
public Observation Get(string agentId, DateTime date) { ... }
}
16. www.devconnections.com
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:
There are eight verbs defined in HTTP 1.1:
16
GET http://localhost:4392/travelers/1 HTTP/1.1
GET
POST
PUT
DELETE
HEAD
OPTIONS
TRACE
CONNECT
17. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
3, 2, 1, ACTIONS!
Actions are matched by HTTP verb
names and the existence of parameterspublic class ProductsController : ApiController
{
public IEnumerable<Product> GetProducts() {...}
public Product GetProductById(int id) {...}
public HttpResponseMessage PostProduct(Product product) {...}
}
DELETE api/products/42
GET api/products
GET api/products/42
POST api/products
19. www.devconnections.com
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
2xx – Success
3xx – Redirection
4xx – Client Error
5xx – Server Error
19
(100 / 101)
(200 – 206)
(300 – 307)
(400 – 417)
(500 – 505)
21. www.devconnections.com
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
21
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;
}
23. www.devconnections.com
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
23
25. www.devconnections.com
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:
25
Type Sub-
type
Type specific parameters
text/html; charset=UTF-8
26. www.devconnections.com
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
26
27. www.devconnections.com
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
27
29. www.devconnections.com
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
29
30. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
VALIDATING USER INPUT
30
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);
}
32. www.devconnections.com
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
32
33. www.devconnections.com
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()
{
}
33
34. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
WEB API AND ODATA
34
[Queryable]
public IQueryable<Agent> GetAgents()
{
return repository.GetAll().AsQueryable();
}
api/agents?$orderby=Name
api/agents?$filter=salary gt 50000
api/agents?$skip=10
api/agents?$skip=50&$top=10
36. www.devconnections.com
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
36
37. www.devconnections.com
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
37
38. www.devconnections.com
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();
38
40. www.devconnections.com
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à!
40
40
41. www.devconnections.com
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
Routing requests to the correct application
Kernel mode SSL (full support as of Windows Server 2008)
Caching responses in kernel mode
Implementing QoS, such as connection limits and timeouts
Want to know more? netsh http show
41
42. www.devconnections.com
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
42
43. www.devconnections.com
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
43
IIS Compression
Modes
Scenarios Considerations
Dynamic
Compression
Small number of requests
Limited network bandwidth
Uses CPU and memory
Not cached
Static Compression
Improve transmission times
Graphic-heavy sites
Can be cached
Uses some CPU
44. www.devconnections.com
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
Less simultaneous opened connections = less CPU
Single connection can pipeline HTTP requests
Fewer TCP connections = less congestion
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
44
– Implementation Dependent
46. www.devconnections.com
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
46
47. www.devconnections.com
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:
Install the Microsoft ASP.NET Web API Self Host
NuGet package
Create host configuration and routing rules
Start the self-hosted server
Under the covers, Web API self-hosting is
handled by WCF
47
48. www.devconnections.com
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
48
49. www.devconnections.com
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
49
50. www.devconnections.com
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
50
52. www.devconnections.com
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
52
53. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
ETAG VERSIONING
53
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;
}
54. www.devconnections.com
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
54
55. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
1. Client requests a secured session
2. Server responds with an X.509 certificate
3. Client verifies certificate’s
authenticity
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
HTTPS - HOW SECURE SOCKETS LAYER WORKS
56. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
CLASSIC HTTP AUTHENTICATION
HTTP uses the Authorization header to pass
authentication data:
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
56
Authorization: Basic eWFuaXY6eWFuaXY=
58. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
HTTP STREAMING
Advantages
Less large memory allocation and buffering
Message can be handled before received completely
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)
58
59. www.devconnections.com
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
59
61. www.devconnections.com
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
61
62. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
WEBSOCKETS IN A GLANCE
Bi-directional TCP channel (full-duplex)
Supports both HTTP and HTTPS (SSL)
Accessible through JavaScript API
Supports cross-domain calls
Client-side - IE10, Chrome, Firefox, .NET 4.5
Server-side – IIS 8, ASP.NET 4.5, SignalR
Standardization is still in progress!!
63. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
ASP.NET SIGNALR 101
Real-time, persistent connection abstraction
over HTTP
Useful for dashboards & monitoring,
collaborative work, job progress, gaming…
SignalR works everywhere
WebSockets
Server Sent Events
Forever Frame
Long Polling
63
64. www.devconnections.com
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
64
65. www.devconnections.com
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
65
67. www.devconnections.com
ASP.NET WEB API AND HTTP FUNDAMENTALS
HTTP Fundamentals via Web API
HTTP Messages
URIs
Routing
Verbs
Controllers and Actions
Status Codes
HttpRequestMessage
HttpResponseMessage
Error Handling
Content Negotiation
Media Type Formatters
OData
Validations
Dependency Resolver
Hosting
HTTP.SYS
IIS 101
HTTP compression
Persisted Connections
Web API Self Hosting
More HTTP and Web API
Caching
Concurrency
Security
Streaming
WebSockets & SignalR
SO WHAT DID WE LEARN TODAY?
67
You are now an HTTP ninja
Rank 1. Just 4 more ranks to go!!
68. www.devconnections.com
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
webapibloggers.com (without www)
Fiddler
www.fiddler2.com
www.youtube.com/watch?v=7Tw5EHvTERc
“Debugging the Web with Fiddler”, Tuesday 2:00PM
68
This Presentation:
sdrv.ms/1eKAsRd
Editor's Notes
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