SlideShare a Scribd company logo
1 of 88
Binu Bhasuran
Microsoft MVP - Visual C#
What is Web API?
What is Web API?
The ASP.NET Web API is an extensible
framework for building HTTP based services
that can be accessed in different applications on
different platforms such as web, windows,
mobile etc.
ASP.NET Web API is an ideal platform for
building RESTful services.
ASP.NET Web API is built on top of ASP.NET and
supports ASP.NET request/response pipeline
ASP.NET Web API maps HTTP verbs to method
names
ASP.NET Web API supports different formats of
response data. Built-in support for JSON, XML,
BSON format.
ASP.NET Web API can be hosted in IIS, Self-
hosted or other web server that supports .NET
4.0+.
ASP.NET Web API framework includes new
HttpClient to communicate with Web API server.
HttpClient can be used in ASP.MVC server side,
Windows Form application, Console application
or other apps.
Choose WCF if you use .NET Framework 3.5. Web
API does not support .NET 3.5 or below.
Choose WCF if your service needs to support
multiple protocols such as HTTP, TCP, Named pipe.
Choose WCF if you want to build service with WS-*
standards like Reliable Messaging, Transactions,
Message Security.
Choose WCF if you want to use Request-Reply, One
Way, and Duplex message exchange patterns.
Choose Web API if you are using .NET
framework 4.0 or above.
Choose Web API if you want to build a service
that supports only HTTP protocol.
Choose Web API to build RESTful HTTP based
services.
Choose Web API if you are familiar with ASP.NET
MVC.
Web API Controller is similar to ASP.NET MVC
controller. It handles incoming HTTP requests
and send response back to the caller.
It must be derived from System.Web.Http.ApiController
class.
It can be created under any folder in the project's root
folder. However, it is recommended to create controller
classes in the Controllers folder as per the convention.
Action method name can be the same as HTTP verb
name or it can start with HTTP verb with any suffix (case
in-sensitive) or you can apply Http verb attributes to
method.
Return type of an action method can be any primitive or
complex type. Learn more about it here.
Web API supports code based configuration. It
cannot be configured in web.config file. We
can configure Web API to customize the
behaviour of Web API hosting infrastructure
and components such as routes, formatters,
filters, DependencyResolver, MessageHandlers,
ParamterBindingRules, properties, services etc.
Web API configuration process starts when the application
starts. It calls
GlobalConfiguration.Configure(WebApiConfig.Register) in
the Application_Start method. The Configure() method
requires the callback method where Web API has been
configured in code. By default this is the static
WebApiConfig.Register() method.
As you can see above, WebApiConfig.Register() method
includes a parameter of HttpConfiguration type which is
then used to configure the Web API. The HttpConfiguration
is the main class which includes following properties using
which you can override the default behaviour of Web API.
Web API supports two types of routing:
Convention-based Routing
Attribute Routing
Convention-based Routing
In the convention-based routing, Web API uses
route templates to determine which controller
and action method to execute. At least one
route template must be added into route table
in order to handle various HTTP requests.
Attribute Routing
Attribute routing is supported in Web API 2. As
the name implies, attribute routing uses [Route()]
attribute to define routes. The Route attribute
can be applied on any controller or action
method.
Attribute Routing
Action methods in Web API controller can have
one or more parameters of different types. It can
be either primitive type or complex type. Web
API binds action method parameters either with
URL's query string or with request body
depending on the parameter type
[FromUri] and [FromBody]
Use [FromUri] attribute to force Web API to get
the value of complex type from the query
string and [FromBody] attribute to get the
value of primitive type from the request body,
opposite to the default rules.
Void
Primitive type or Complex type
HttpResponseMessage
IHttpActionResult
.
Web API controller always returns an object of
HttpResponseMessage to the hosting
infrastructure. The following figure illustrates
the overall Web API request/response pipeline.
The IHttpActionResult was introduced in Web
API 2 (.NET 4.5). An action method in Web API
2 can return an implementation of
IHttpActionResult class which is more or less
similar to ActionResult class in ASP.NET MVC.
Create Custom Result Type
You can create your own custom class as a result
type that implements IHttpActionResult
interface.
Media Type
Content-Type
Media Type
Media type (aka MIME type) specifies the
format of the data as type/subtype e.g.
text/html, text/xml, application/json,
image/jpeg etc.
Content-Type
In HTTP request, MIME type is specified in the
request header using Accept and Content-
Type attribute. The Accept header attribute
specifies the format of response data which the
client expects and the Content-Type header
attribute specifies the format of the data in the
request body so that receiver can parse it into
appropriate format.
Web API handles JSON and XML formats based
on Accept and Content-Type headers. But, how
does it handle these different formats?
The answer is: By using Media-Type formatters.
Media type formatters are classes responsible
for serializing request/response data so that
Web API can understand the request data
format and send data in the format which client
expects.
BSON Formatter
Web API also supports BSON format. As the
name suggests, BSON is binary JSON, it is a
binary-encoded serialization of JSON-like
documents. Currently there is very little support
for BSON and no JavaScript implementation is
available for clients running in browsers. This
means that it is not possible to retrieve and
automatically parse BSON data to JavaScript
objects.
BSON Formatter
Web API includes built-in formatter class
BsonMediaTypeFormatter for BSON but it
is disabled by default.
JSON Formatter
The JsonMediaTypeFormatter converts JSON
data in an HTTP request into CLR objects (object
in C# or VB.NET) and also converts CLR objects
into JSON format that is embeded within HTTP
response.
Configure JSON Serialization
XML Formatter
The XmlMediaTypeFormatter class is
responsible for serializing model objects into
XML data. It uses
System.Runtime.DataContractSerializer class to
generate XML data.
Web API includes filters to add extra logic
before or after action method executes. Filters
can be used to provide cross-cutting features
such as logging, exception handling,
performance measurement, authentication and
authorization.
Asp.net web api
Asp.net web api
Asp.net web api
Asp.net web api
Asp.net web api
Asp.net web api

More Related Content

What's hot

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance Topics
Ali Taki
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
KMS Technology
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
Khaled Musaied
 

What's hot (20)

ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance Topics
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
MVC - Introduction
MVC - IntroductionMVC - Introduction
MVC - Introduction
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
Introduction To Single Page Application
Introduction To Single Page ApplicationIntroduction To Single Page Application
Introduction To Single Page Application
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Asp.net
 Asp.net Asp.net
Asp.net
 
Servlet
Servlet Servlet
Servlet
 
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
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
SignalR with asp.net
SignalR with asp.netSignalR with asp.net
SignalR with asp.net
 
REST API
REST APIREST API
REST API
 
laravel.pptx
laravel.pptxlaravel.pptx
laravel.pptx
 
What is an API?
What is an API?What is an API?
What is an API?
 
REST-API introduction for developers
REST-API introduction for developersREST-API introduction for developers
REST-API introduction for developers
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 

Similar to Asp.net web api

An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
vikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
vikram singh
 
quickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcquickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvc
jorgesimao71
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
raviIITRoorkee
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
AMARAAHMED7
 
Xml web services
Xml web servicesXml web services
Xml web services
Raghu nath
 

Similar to Asp.net web api (20)

Implementation web api
Implementation web apiImplementation web api
Implementation web api
 
Web API with ASP.NET MVC by Software development company in india
Web API with ASP.NET  MVC  by Software development company in indiaWeb API with ASP.NET  MVC  by Software development company in india
Web API with ASP.NET MVC by Software development company in india
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Web api
Web apiWeb api
Web api
 
quickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcquickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvc
 
Rest web service
Rest web serviceRest web service
Rest web service
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01
 
Rest API Automation with REST Assured
Rest API Automation with REST AssuredRest API Automation with REST Assured
Rest API Automation with REST Assured
 
ASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web applicationASP.NET Core Web API documentation web application
ASP.NET Core Web API documentation web application
 
UNIT 3 web iiiBCA.pptx
UNIT 3 web iiiBCA.pptxUNIT 3 web iiiBCA.pptx
UNIT 3 web iiiBCA.pptx
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
Marata
MarataMarata
Marata
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)
 
Day7
Day7Day7
Day7
 
Java servlets
Java servletsJava servlets
Java servlets
 
Xml web services
Xml web servicesXml web services
Xml web services
 
Salesforce Integration
Salesforce IntegrationSalesforce Integration
Salesforce Integration
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 

More from Binu Bhasuran

Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf service
Binu Bhasuran
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
Binu Bhasuran
 

More from Binu Bhasuran (13)

Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
Microsoft Azure solutions - Whitepaper
Microsoft Azure solutions - WhitepaperMicrosoft Azure solutions - Whitepaper
Microsoft Azure solutions - Whitepaper
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Microsoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkMicrosoft Managed Extensibility Framework
Microsoft Managed Extensibility Framework
 
Restful Services With WFC
Restful Services With WFCRestful Services With WFC
Restful Services With WFC
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Wcf development
Wcf developmentWcf development
Wcf development
 
.Net platform an understanding
.Net platform an understanding.Net platform an understanding
.Net platform an understanding
 
Biz talk
Biz talkBiz talk
Biz talk
 
Moving from webservices to wcf services
Moving from webservices to wcf servicesMoving from webservices to wcf services
Moving from webservices to wcf services
 
Model view view model
Model view view modelModel view view model
Model view view model
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf service
 
Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#Asynchronous programming in .net 4.5 with c#
Asynchronous programming in .net 4.5 with c#
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Recently uploaded (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Asp.net web api

  • 2. What is Web API?
  • 3. What is Web API?
  • 4. The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such as web, windows, mobile etc.
  • 5.
  • 6. ASP.NET Web API is an ideal platform for building RESTful services. ASP.NET Web API is built on top of ASP.NET and supports ASP.NET request/response pipeline ASP.NET Web API maps HTTP verbs to method names ASP.NET Web API supports different formats of response data. Built-in support for JSON, XML, BSON format.
  • 7. ASP.NET Web API can be hosted in IIS, Self- hosted or other web server that supports .NET 4.0+. ASP.NET Web API framework includes new HttpClient to communicate with Web API server. HttpClient can be used in ASP.MVC server side, Windows Form application, Console application or other apps.
  • 8.
  • 9.
  • 10. Choose WCF if you use .NET Framework 3.5. Web API does not support .NET 3.5 or below. Choose WCF if your service needs to support multiple protocols such as HTTP, TCP, Named pipe. Choose WCF if you want to build service with WS-* standards like Reliable Messaging, Transactions, Message Security. Choose WCF if you want to use Request-Reply, One Way, and Duplex message exchange patterns.
  • 11. Choose Web API if you are using .NET framework 4.0 or above. Choose Web API if you want to build a service that supports only HTTP protocol. Choose Web API to build RESTful HTTP based services. Choose Web API if you are familiar with ASP.NET MVC.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16. Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller.
  • 17.
  • 18.
  • 19. It must be derived from System.Web.Http.ApiController class. It can be created under any folder in the project's root folder. However, it is recommended to create controller classes in the Controllers folder as per the convention. Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes to method. Return type of an action method can be any primitive or complex type. Learn more about it here.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24. Web API supports code based configuration. It cannot be configured in web.config file. We can configure Web API to customize the behaviour of Web API hosting infrastructure and components such as routes, formatters, filters, DependencyResolver, MessageHandlers, ParamterBindingRules, properties, services etc.
  • 25.
  • 26.
  • 27. Web API configuration process starts when the application starts. It calls GlobalConfiguration.Configure(WebApiConfig.Register) in the Application_Start method. The Configure() method requires the callback method where Web API has been configured in code. By default this is the static WebApiConfig.Register() method. As you can see above, WebApiConfig.Register() method includes a parameter of HttpConfiguration type which is then used to configure the Web API. The HttpConfiguration is the main class which includes following properties using which you can override the default behaviour of Web API.
  • 28.
  • 29. Web API supports two types of routing: Convention-based Routing Attribute Routing
  • 30. Convention-based Routing In the convention-based routing, Web API uses route templates to determine which controller and action method to execute. At least one route template must be added into route table in order to handle various HTTP requests.
  • 31.
  • 32.
  • 33. Attribute Routing Attribute routing is supported in Web API 2. As the name implies, attribute routing uses [Route()] attribute to define routes. The Route attribute can be applied on any controller or action method.
  • 35. Action methods in Web API controller can have one or more parameters of different types. It can be either primitive type or complex type. Web API binds action method parameters either with URL's query string or with request body depending on the parameter type
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43. [FromUri] and [FromBody] Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50. Void Primitive type or Complex type HttpResponseMessage IHttpActionResult .
  • 51.
  • 52.
  • 53.
  • 54.
  • 55. Web API controller always returns an object of HttpResponseMessage to the hosting infrastructure. The following figure illustrates the overall Web API request/response pipeline.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60. The IHttpActionResult was introduced in Web API 2 (.NET 4.5). An action method in Web API 2 can return an implementation of IHttpActionResult class which is more or less similar to ActionResult class in ASP.NET MVC.
  • 61.
  • 62. Create Custom Result Type You can create your own custom class as a result type that implements IHttpActionResult interface.
  • 63.
  • 65. Media Type Media type (aka MIME type) specifies the format of the data as type/subtype e.g. text/html, text/xml, application/json, image/jpeg etc.
  • 66. Content-Type In HTTP request, MIME type is specified in the request header using Accept and Content- Type attribute. The Accept header attribute specifies the format of response data which the client expects and the Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74. Web API handles JSON and XML formats based on Accept and Content-Type headers. But, how does it handle these different formats? The answer is: By using Media-Type formatters.
  • 75. Media type formatters are classes responsible for serializing request/response data so that Web API can understand the request data format and send data in the format which client expects.
  • 76.
  • 77. BSON Formatter Web API also supports BSON format. As the name suggests, BSON is binary JSON, it is a binary-encoded serialization of JSON-like documents. Currently there is very little support for BSON and no JavaScript implementation is available for clients running in browsers. This means that it is not possible to retrieve and automatically parse BSON data to JavaScript objects.
  • 78. BSON Formatter Web API includes built-in formatter class BsonMediaTypeFormatter for BSON but it is disabled by default.
  • 79. JSON Formatter The JsonMediaTypeFormatter converts JSON data in an HTTP request into CLR objects (object in C# or VB.NET) and also converts CLR objects into JSON format that is embeded within HTTP response.
  • 81. XML Formatter The XmlMediaTypeFormatter class is responsible for serializing model objects into XML data. It uses System.Runtime.DataContractSerializer class to generate XML data.
  • 82. Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.

Editor's Notes

  1. ASP.NET Web API is a framework for building HTTP services that can be accessed from any client including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Framework. Before we understand what is Web API, let's see what is an API (Application Programing Interface).
  2. As per Wikipedia's Definition of API: In computer programming, an application programming interface (API) is a set of subroutine definitions, protocols, and tools for building software and applications. To put it in simple terms, API is some kind of interface which has a set of functions that allow programmers to access specific features or data of an application, operating system or other services.
  3. It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view. It is like a webservice or WCF service but the exception is that it only supports HTTP protocol.
  4. It works more or less the same way as ASP.NET MVC web application except that it sends data as a response instead of html view. It is like a webservice or WCF service but the exception is that it only supports HTTP protocol.
  5. In a typical console application in C#, execution starts from the Main() function. The Main() function controls the flow of a program or in other words sequence of user interaction. Consider the following simple console program In the above example, the Main() function of the program class controls the flow of a program. It takes user's input for the first Name and last name. It saves the data, continues or exits the console depending upon the user's input. So here, flow of the control through the Main() function.
  6. Fiddler Postman
  7. Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder. The name of a controller class must end with "Controller" and it must be derived from System.Web.Http.ApiController class. All the public methods of the controller are called action methods.
  8. If you want to write methods that do not start with an HTTP verb then you can apply the appropriate http verb attribute on the method such as HttpGet, HttpPost, HttpPut etc. same as MVC controller.
  9. In the above example, School route is configured before DefaultApi route. So any incoming request will be matched with the School route first and if incoming request url does not match with it then only it will be matched with DefaultApi route. For example, request url is http://localhost:1234/api/myschool is matched with School route template, so it will be handled by SchoolController.
  10. In the above example, the Route attribute defines new route "api/student/names" which will be handled by the Get() action method of StudentController. Thus, an HTTP GET request http://localhost:1234/api/student/names will return list of student names.
  11. By default, if parameter type is of .NET primitive type such as int, bool, double, string, GUID, DateTime, decimal or any other type that can be converted from string type then it sets the value of a parameter from the query string. And if the parameter type is complex type then Web API tries to get the value from request body by default.
  12. As you can see above Get action method includes id parameter of int type. So, Web API will try to extract the value of id from the query string of requested URL, convert it into int and assign it to id parameter of Get action method. For example, if an HTTP request is http://localhost/api/student?id=1 then value of id parameter will be 1. Followings are valid HTTP GET Requests for the above action method. http://localhost/api/student?id=1 http://localhost/api/student?ID=1
  13. As you can see above, Post() action method includes primitive type parameters id and name. So, by default, Web API will get values from the query string. For example, if an HTTP POST request is http://localhost/api/student?id=1&name=steve then the value of id will be 1 and name will be "steve" in the above Post() method.
  14. Web API will extract the JSON object from the Request body above and convert it into Student object automatically because names of JSON object properties matches with the name of Student class properties (case-insensitive).
  15. The above Post method includes both primitive and complex type parameter. So, by default , Web API will get the id parameter from query string and student parameter from the request body.
  16. The above Post method includes both primitive and complex type parameter. So, by default , Web API will get the id parameter from query string and student parameter from the request body. Parameter binding for Put and Patch method will be the same as Post method in Web API.
  17. By default, if parameter type is of .NET primitive type such as int, bool, double, string, GUID, DateTime, decimal or any other type that can be converted from string type then it sets the value of a parameter from the query string. And if the parameter type is complex type then Web API tries to get the value from request body by default.
  18. In the above example, Get method includes complex type parameter with [FromUri] attribute. So, Web API will try to get the value of Student type parameter from the query string. For example, if an HTTP GET request http://localhost:xxxx/api/student?id=1&name=steve then Web API will create Student object and set its id and name property values to the value of id and name query string
  19. As you can see above, we have applied [FromUri] attribute with the Student parameter. Web API by default extracts the value of complex type from request body but here we have applied [FromUri] attribute. So now, Web API will extract the value of Student properties from the query string instead of request body.
  20. Primitive or Complex Type An action method can return primitive or other custom complex types as other normal methods.
  21. As you can see above, GetId action method returns an integer and GetStudent action method returns a Student type. An HTTP GET request http://localhost:xxxx/api/student?name=john will return following response in Fiddler. Primitive Return Type in Response
  22. An HTTP GET request http://localhost:xxxx/api/student?id=1 will return following response in Fiddler.
  23. As you can see in the above figure, the Web API controller returns HttpResponseMessage object. You can also create and return an object of HttpResponseMessage directly from an action method. The advantage of sending HttpResponseMessage from an action method is that you can configure a response your way. You can set the status code, content or error message (if any) as per your requirement.
  24. You can create your own class that implements IHttpActionResult or use various methods of ApiController class that returns an object that implement the IHttpActionResult.
  25. Web API converts request data into CLR object and also serialize CLR object into response data based on Accept and Content-Type headers. Web API includes built-in support for JSON, XML, BSON, and form-urlencoded data. It means it automatically converts request/response data into these formats OOB (out-of the box).
  26. As you can see above, the Post() action method accepts Student type parameter, saves that student into DB and returns inserted student with generated id. The above Web API handles HTTP POST request with JSON or XML data and parses it to a Student object based on Content-Type header value and the same way it converts insertedStudent object into JSON or XML based on Accept header value.
  27. Internally, JsonMediaTypeFormatter uses third-party open source library called Json.NETto perform serialization.
  28. JSON formatter can be configured in WebApiConfig class. The JsonMediaTypeFormatter class includes various properties and methods using which you can customize JSON serialization. For example, Web API writes JSON property names with PascalCase by default. To write JSON property names with camelCase, set the CamelCasePropertyNamesContractResolver on the serializer settings as shown below.
  29. Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System.Web.Http.Filters namespace. However, System.Web.Http.Filters includes other interfaces and classes that can be used to create filter for specific purpose.