C# ASP - Net Web API Application Development
C# ASP - Net Web API Application Development
WEB-API
C#
1. ASP.NET WEB API INTRODUCTION
Presentati
Data Business
on
Assembly
Assembly (.dll) (.exe/.dll)
Process Process
C#
InterProcess Communication
END POINT/IP+PORT
Assembly Assembly
(.dll) (.dll)
Process Process
END POINT/IP+PORT
Communication Protocol
TCP/IP/UDP/HTTP
C#
Firewall
XML/JSON
Light weight WEB API SERIALIZED
Data Business XML/JSON JAVA/C++
Light weight
WEB API SERIALIZED JAVA/C++ PHP/RUBY
PHP/RUBY Platform
Assembly XML/JSON
SERIALIZED JAVA/C++ Platform
(.dll) PHP/RUBY
Platform
Process
WCF Same Platform
XML+HTT .Net (Assembly
ENDPOINT P Reference .dll) Same Platform
/IP+PORT WCF .Net (Assembly
WCF SERVICE Reference .dll) JAVA/C++
XML+HTTP
WCF PHP/RUBY
ASP.NET WEB API Platform
XML+HTTP
C#
Firewall
XML/JSON
Light weight WEB API SERIALIZED
Data Business XML/JSON JAVA/C++
Light weight
WEB API SERIALIZED JAVA/C++ PHP/RUBY
PHP/RUBY Platform
Assembly XML/JSON
SERIALIZED Platform
(.dll)
Process
WCF
XML+HTT
ENDPOINT P
Web services
• A web service is a collection of protocols and
standards used for exchanging data between
applications or systems.
WebServices are published, described and located over Internet.
C#
Characteristics
1. A Web Service is accessible over the Web.
2. Web Services communicate using platform-independent
and language-neutral Web protocols.
3. A Web Service shares schemas and contracts/interface
that can be called from another program.
4. A Web Service is registered and can be located through
a Web Service Registry.
5. Web Services support loosely coupled connections
between systems.
C#
SOAP
• Simple Object Access
Protocol
• SOAP is an open protocol
specification defining a
uniform way of performing
RPCs using HTTP as the
underlying communications
protocol with XML for the
data serialization.
PORT 80 or HTP
C#
SOAP-Packet
HTTP Packet
HTTP Header
HTTP Body
SOAP Messages
• SOAP provides a standard ‘envelope’ within which a message
can be delivered.
• SOAP is mechanism (protocol) for transferring information
(messages) between applications which may be widely
distributed.
• SOAP says nothing about the content of the message – the
sender and the receiver must understand the message for
themselves.
• SOAP is part of a communication stack.
Web Services
SOAP
WCF
SOAP STRUCTURE
• Each SOAP message will Transport protocol
MIME header
have:
SOAP ENVELOPE
– An Envelope
– A Header (optional) SOAP HEADER
– A Body
– The Body may contain a SOAP BODY
Fault element FAULT
SOAP Structure(2)
• The envelope wraps the entire soap document
• The header allows additional information to be
passed as well as the body of the document – e.g.
Authentication
• The body element contains the core of the SOAP
document – this will contain either the RPC call or
the XML message itself
• The fault information will contain any exception
information
C#
</SOAP-ENV:Header
<SOAP_ENV:Body>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
C#
<SOAP-ENV:Envelope xmlns:SOAP_ENV=“http://schemas.xmlsoap.org/soap/envelope/”
xmlns:xsi=“http://www.w3c.org/1999/XMLSchema-instance”
xmlns:xsd=“http://www.w3c.org/1999/XMLSchema”>
</SOAP-ENV:Envelope>
C#
SOAP RPC
• SOAP RPC messages contain XML that
represents a method call or method response
SOAP Faults
• SOAP errors are handled using a specialised
envelope known as a Fault Envelope
• A SOAP Fault is a special element which must
appear as an immediate child of the body
element
• <faultcode> and <faultstring> are required.
C#
A SOAP fault
<?xml version=‘1.0’ encoding=‘UTF-8’?>
<SOAP-ENV:Envelope
xmlns:SOAP_ENV=“http://schemas.xmlsoap.org/soap/envelope/”
xmlns:xsi=“http://www.w3c.org/1999/XMLSchema-instance”
xmlns:xsd=“http://www.w3c.org/1999/XMLSchema”>
<SOAP_ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>Test fault</faultstring>
<faultactor>/soap/servlet/rpcrouter</faultactor>
<detail>
..
</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
C#
SOAP Attachment
Transport protocol
• Large quantities or binary data
MIME header
may not fit well into a XML
SOAP message. SOAP ENVELOPE
SOAP HEADER
• In which case it can be sent ‘out
of band’ by attaching it to a
SOAP message SOAP BODY
FAULT
• Analogy : email attachments.
Attachment
C#
<attachment href=“{URL}”/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
C#
SOAP HTTP
• SOAP is an XML based • HTTP can serve any content
encoding of messages that over HTTP such as HTML,
are typically sent over HTTP, images, sound, video etc.
but could be sent over • HTTP is overTCP/IP
SMTP or even FTP • HTTP based APIs refer to
• SOAP sites on top of HTTP APIs that are exposed as
• Generally require a toolkit one or more HTTP URIs and
and more processing power. typical responses are in XML
/ JSON. Response schemas
are custom per object
URL
• Uniform resource locator
– http://www.google.com/
– https://www.google.com/username/logo.jpg
http://www.askapache.com/online-tools/http-headers-tool/
Content Types
• Content type that a server specifies relies on
the Multi-purpose Internet Mail Extensions
(MIME)
Type/SubType Description
Application/atom+xml Atom feed
Application/json JSON data
Image/gif GIF image
Image/png PNG image
Video/mp4 Mp4 video
Text/xml Xml
Text/html Html
Text/plain Just text
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 24
C#
HTTP
• Ubiquitous (common)
• Interoperable
• Scalable
• Flexible
• Mature
• Simple
HTTP
• Stateless – Each HTTP is designed
transaction between the
client and server is as a stateless
independent and no state is protocol meaning
set based on a previous
transaction or condition. each request
• Uses requests from the response
client to the server
and responses from the transaction is
server to the client for independent
sending and receiving data.
• The Web client and the Web server are application programs
• Application layer programs do useful work like retrieving Web
pages, sending and receiving email or transferring files
• Lower layers take care of the communication details
• The client and server send messages and data without knowing
anything about the communication network
C#
HTTP
HTTP: hypertext transfer protocol
•The rules governing the conversation between a Web client and a
Web server
•Request-response protocol
•It is a stateless (does not maintain a state of a session) and
asynchronous( an html document is loaded asynchronous by the
browser as soon as parts of it are available)
Layer Function
Application Do useful work like Web browsing, email,
and file transfer
Lower layers Handle communication between the client
and server
HTTP Request
HTTP Response
Client Server
• I would like to open a
connection • OK
• Display response
• Close connection
• OK
HTTP Request
•
Request-Method is: Request-header can have the
following fields (selection):
• GET – request whatever information is
identified by the Request-URL – Accept : MIME types of resources
accepted by browser
• POST – request that server accepts the
entity enclosed in the request – Accept-Charset : charset accepted by
• OPTIONS - request for information about browser
communication options – Accept-Encoding : encoding accepted
• PUT – request that the enclosed entity be by browser
stored under the Request-URL – Accept-Language : language accepted
• DELETE – request that the server delete by browser
the resource identified by Request-URL
– Authorization : user-agent wishes to
• TRACE – invoke a remote, application- authenticate itself with a server
layer loopback of the request message
– Host : the host Request-URL points to
• CONNECT – used by proxies in SSL
connections – Referer : the URL of document
• HEAD – identical to GET, but server must refering this URL
not return a message body in response – User-Agent : Firefox, Safari, IE
GET POST
HEAD PUT
OPTIONS WRITE
DELETE
READ
http methods that do not modify resources http methods that modify resources
HTTP vs HTTPS
HTTP HTTPS
• It is hypertext transfer • It is hypertext transfer
protocol protocol with secure
• It is not secure and • It is secure and reliable
unreliable • Https urls being with https
• HTTP urls begin with http:// • It uses port 443 by default
• It uses port 80 by default • It is designed to withstand
• It is subject to man-in-the- such attacks and is
middle and eavesdropping considered secure against
attacks such attacks
http://www.rexswain.com/httpview.html
http://headers.cloxy.net/
Request Messages
[method] [URL] [version]
[headers]
[body]
GET http://www.sycliq.com/articles/index.aspx
Host: google.com
Accept-Language : en-EN
Date: FRI, 19 Jan, 2016 10:10:26 GMT
Full Request
Get/HTTP/1.1
Host: sycliq.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows 10; WOW64) Chrome/16.0.912.75
Accept: text/html, application/xhtml+xml, application/xml;q=0.9,*/*; q=0.8
Referer: http://www.google.com/url?&q=iot
Accept-Encoding: gzip, defalte, sdch
Accept-Language: en-Us, en; q=0.8
Accept-Charset: ISO-8859-1, utf-8;q=0.7,*q=0.3
http://www.askapache.com/online-tools/http-headers-tool/
HTTP RESPONSE
https://curlbuilder.com/
[version] [status][reason]
[headers]
[body]
HTTP Header
Request
Response
Content Negotiation
• It is the process of selecting the • In general a client sends the
best representation for a given Accept parameter in the Request
response when there are multiple Header to determine the
representations available. response.
• Content negotiation (conneg) in • In .NET, it really comes down to
the ASP.NET Web API is an deciding how to send down your
intrinsic server-driven mechanism CLR object to the client, over
used to determine, based on the HTTP or from the ASP.NET Web
client's request, which media API perspective, serialization is
type formatter (out of the box the process of translating a .NET
there are 4 media type Common Language Runtime (CLR)
formatters) to be used to return type into a format that can be
an API response. transmitted over HTTP. The
default formats are either JSON
or XML.
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 44
C#
Content Negotiation
• Core mechanism of
HTTP
• Client specific desired
formats using
AcceptHeader
Summary
• We understood the evolution of web services
to support cross platform applications using
light weight http application protocol.
ASP.NET
What?
• A fully supported and extensible framework for
building HTTP based endpoints
• Built on the top of ASP.NET
– Mostly ASP.NET Routing
• Released with ASP.NET MVC4
– Not linked to MVC – you can use alone, with MVC4 or you
can use with ASP.NET web forms
– Available via NuGET
• Also includes a new HTTP Client
Why?
• First-class modern HTTP programming model
• Easily map resources to URIs and implement the uniform
interface of HTTP
• Rich support for formats and HTTP content negotiation
• Request validation
• Enable hypermedia with link generations
• Separate out cross cutting concerns (like authorization,
caching)
• Help Page generation
• Flexible hosting
• Light-weight testable, scales
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 53
C#
Why?
• You are building
– An HTML5 application that needs a services layer
– A mobile application that needs a services layer
– A client-server desktop application that needs a
services layer
– Reach more clients (Native Mobile Applications,
Cross platform applications)
– Scale with the cloud
– Embrace HTTP as an Application protocol
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 54
C#
What’s new?
ASP.NET Web API 2 ASP.NET Web 2.1
• Attribute Routing • Attribute Routing
• Improved testability improvements
(IHTTPActionResult, • Global error handling
HttpRequestContext)
• Odata: $select, $expand, • Help page improvements
$value,$batch • IgnoreRoute support
• Request batching • BSON formatter
• OWIN (Open Web Interface for
.NET) Integration
• Better async filter
• Portable Web API Clients • Portable query building and
• Web API Security parsing
(CORS,OAuth2.0, Authentication
filters, filter overrides)
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 57
C#
https://www.hurl.it/
Is this REST?
• The ASP.NET Web API doesn’t dictate an
architectural style
• However you can build a RESTful service on
top of it
– It does not get in your way if you want to design
using the REST architectural style
WCF Challenges
• It is also based on SOAP and return • To use WCF as WCF Rest service you
data in XML form. have to enable webHttpBindings.
• It is the evolution of the web • It support HTTP GET and POST verbs
service(ASMX) and support various by [WebGet] and [WebInvoke]
protocols like TCP, HTTP, HTTPS, attributes respectively.
Named Pipes, MSMQ. • To enable other HTTP verbs you have
• The main issue with WCF is, its to do some configuration in IIS to
tedious and extensive configuration. accept request of that particular verb
• It is not open source but can be on .svc files
consumed by any client that • Passing data through parameters
understands xml. using a WebGet needs configuration.
• It can be hosted with in the The UriTemplate must be specified
applicaion or on IIS or using window • It support XML, JSON and ATOM data
service. format.
• Choose WCF when you want to create a service that should support
special scenarios such as one way messaging, message queues, duplex
communication etc.
• Choose WCF when you want to create a service that can use fast transport
channels when available, such as TCP, Named Pipes, or maybe even UDP
(in WCF 4.5), and you also want to support HTTP when all other transport
channels are unavailable.
• Choose Web API when you want to create a resource-oriented services
over HTTP that we can use the full features of HTTP (like URIs,
request/response headers, caching, versioning, various content formats).
• Choose Web API when you want to expose your service to a broad range
of clients including browsers, mobiles, iphone and tablets.
INTRODUCTION, ROUTING,
ATTRIBUTE ROUTING
© Syed Awase 2015-16 - ASP.Net MVC Ground
3/23/2016 65
Up
C#
Getting Started
• Create a WebAPI
Project
• Create an ASP.NET
Project and add a Web
API Project
• Create any project!
– Install-package
Microsoft.AspNet.WebApi.SelfHost
– Using NuGet
WebApiConfig.cs
WebAPI
ASP.NET MVC5
Project
Global.asax Global.asax
Conventional Routing
• Convention-based routing, you • Advantage being that
define one or more route templates are defined in a
templates, which are basically
parameterized strings.
single place and routing
• ASP.NET Hosting Layer Maps URIs
rules are applied
and Verbs to controller consistently across
– Must derive from APIController controllers
• New Extension Method for • ASP.NET Routing is the most
Routing common way to map URIs
– MapHttpRoute
and Verbs to your methods
– Registers a differentHandler to
the routing Infrastructure – Not the only way however
• HttpControllerHandler – Self Hosting can use this
system or replace it with your
own.
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 68
C#
Conventional Routing
Conventional Routing
Attribute Routing
• Convention-based routing • Attribute routing, is
makes it hard to support trivial to define a route
certain URI patterns that
for this URL.
are common in RESTful
APIs. • Simply by adding an
• E.g. Customers have orders, [attribute] to the
movies have actors, books controller action
have authors
• It’s natural to create URIs
that reflect these relations
– /customers/1/orders
Attribute routing
set a common prefix for an entire controller
by using the [RoutePrefix] attribute:
WebAPI
Configuration
Services
And WebAPI
Routes
Route constraints
Route constraints let you restrict how the parameters
in the route template are matched. The general syntax
is "{parameter:constraint}"
Supported constraints
Constraint Description Example
{x:regex(^\d{3}-\d{3}-
regex Matches a regular expression.
\d{4}$)}
[OR]
Route Name
In Web API, every route has a name. Route names are useful for generating links,
so that you can include a link in an HTTP response.
Route Order
When the framework tries to match a URI with a route, it evaluates the routes in a
particular order. To specify the order, set the RouteOrder property on the route
attribute. Lower values are evaluated first. The default order value is zero.
Route Order
1. orders/details
2. orders/{id}
3. orders/{customerName}
4. orders/{*date}
5. orders/pending
SUMMARY
• Approaches for creating web api 2
applications
• Conventional routing using MapHttpRoute
• Attribute Routing approaches
• In fact, you can combine both techniques in
the same project.
ACTION RESULTS
• Converting the return value from a controller action into an HTTP
response message.
• WEB API 1 : two ways of creating response from an API action
– Either return a specific object instance (or void) and let the Web API pipeline
convert that to an HttpResponseMessage for you
– Return a raw HttpResponseMessage, where the user has to construct it
manually and bypass all of the internal Web API mechanisms (formatters,
content negotiation).
• WEB API 2: IHTTPACTIONRESULT is a kind of wrap of
HTTPRESPONSEMESSAGE. It contains ExecuteAsync method to create an
HttpResponseMessage, further simplifies unit testing of your controller.
The return type are kind of strongly typed classes serialized by Web API
using media formatter into the response body.
– Drawbacks being one cannot directly return an error code, such as 404. Instead you
can only throw and HttpResponseException error.
VOID
• If the return type is
void, Web API simply
returns an empty HTTP
response with status
code 204 (NO
CONTENT)
HttpResponseMessage
• HttpResponseMessage
return type, converts the
return value directly into
an HTTP response
message using the
properties of the
HttpResponseMessage
object to populate the
response.
• The option gives you a lot
of control over the
response message
HttpResponseMessage
IHttpActionResult
• Introduced in Web API2
• IHttpActionResult Interface defines an
HttpResponseMessage factory
• Advantages of using IHttpActionResult
– Simplifies unit testing webapi controllers
– Moves common logic for creating HTTP responses into
separate classes
– Makes the intent of the controller action clearer, by hiding
the low-level details of constructing the response
IHttpActionResult
Assemblies
System.Net.Http • Client and raw messaging types
UNIFORM INTERFACE
REST
• Representational State Transfer
• Architecture for building systems ( by Roy Fielding)
• Based on the advantages of the Web
– URIs
– Uniform Interface
– Stateless
– Hypermedia-driven(i.e links)
– Cache-ability
Uniform interface
• No Side-effects (Safe)
GET • Idempotent(calling a million times has the same effect as one request)
• Retrieves resource
• Cacheable
Verbs to Attributes
• If you don’t want to name your methods with the Convention,
you can add attributes to your methods
– Name method whatever you’d like
– Routing still picks Controller
• AcceptVerbs
– Can specify multiple verbs to one method
• Specific attributes
– HttpGet
– HttpPost
– HttpPut
– HttpDelete
Content Negotiation
• Dynamically determining the media type of a
resource based on client request
– Client sends Accept header with 1...N media types
(XML/JSON)
– Server sends back appropriate response with Content-Type
header
– Client also sends Content-Type header when sending a
body
• Web API provides automatic content negotiation
• Implemented using MediaTypeFormatter base class
– More on this in extensibility Module
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 105
C#
id – parameter is of simple type and gets the value from the request URI
[FromURI]
• To force WEB API
to read a complex
type from the URI
• Add the [FromUri]
attribute to the
parameter.
The client can put the Latitude and Longitude values in the query string and Web API
will use them to construct a GeoPoint
http://localhost/api/geopoint/?Latitude=47.678558&Longitude=-
122.130989
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 108
C#
[FromBody]
• To force WEB API to
read a simple type
from the request
body, add the
[FromBody] attribute
to the parameter
• At most one Content-Type: application/json
parameter is allowed
to read from the
message body.
The reason for this rule is that the request body might be stored in a non-
buffered stream that can only be read once.
HTTP-Diving Deeper
• Routing and controllers take care of the basics of HTTP
– URI + Verb
• What if you want to reach down further into the HTTP stack?
– Send back particular return methods
– Interrogate additional HTTP headers
• HttpRequestMessage/HttpResponseMessage are the answer
in the Web API
– HttpRequestMessage can replace body parameter
– HttpResponseMessage can replace return parameter
DATA LAYER EF
EF DB FIRST
DB Connection Settings
Service Layer
ApiController
Connection String
Web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=DESKTOP-
I57JOS9\SQLEXPRESS2014;Initial Catalog=Work;Integrated Security = SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
Enable-Migrations
Add-Migration Initial
Update-Database
Relationship FixUP
• Navigation properties are not loaded explicitly
• Cyclic Reference
MEDIATYPEFORMATTERS IN WEB
API
© Syed Awase 2015-16 - ASP.Net MVC Ground
3/23/2016 141
Up
C#
MediaTypeFormatter
• To seamlessly convert HTTP data to/from .NET types.
• media type: refers to the value of the content-type
header within an HTTP request and response.
– Media types allow agent (client) and server to define the
type of the data sent in the HTTP body (payload).
– It is also used within the accept header in the request to
allow content negotiation, i.e. client notifies the server of
the media types it accepts/prefers.
Using MediaTypeFormatters
• Global formatters sitting in
the formatters property of • For Self-Hosting
HttpConfiguration. – Create a
• If you are using ASP.NET HttpSelfHostConfiguration
hosting (IIS, Cassini, etc) object which has
then you can use formatters property.
GlobalConfiguration.Configuration
to access the instance
of HttpConfiguration
containing formatters.
App_Start-> WebApiConfig.cs
Result in Output window
3/23/2016 © Syed Awase 2015-16 - ASP.Net MVC Ground Up 144
C#
MediaTypeFormatters