SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere Àhnliche Inhalte

Was ist angesagt?

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 OverviewShahed Chowdhuri
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsIdo Flatow
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkShravan A
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.jsEmanuele DelBono
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
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 DEVELOPMENTDr. Awase Khirni Syed
 

Was ist angesagt? (20)

REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
REST API
REST APIREST API
REST API
 
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
 
Web api
Web apiWeb api
Web api
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Rest API
Rest APIRest API
Rest API
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity Framework
 
Spring boot
Spring bootSpring boot
Spring boot
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Spring boot
Spring bootSpring boot
Spring boot
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
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
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
Asp.net
 Asp.net Asp.net
Asp.net
 

Ähnlich wie Asp.net 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 indiaiFour Institute - Sustainable Learning
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Web api
Web apiWeb api
Web apiudaiappa
 
quickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcquickguide-einnovator-7-spring-mvc
quickguide-einnovator-7-spring-mvcjorgesimao71
 
Rest web service
Rest web serviceRest web service
Rest web serviceHamid Ghorbani
 
Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01Anintroductiontojavawebtechnology 090324184240-phpapp01
Anintroductiontojavawebtechnology 090324184240-phpapp01raviIITRoorkee
 
Rest API Automation with REST Assured
Rest API Automation with REST AssuredRest API Automation with REST Assured
Rest API Automation with REST AssuredTO THE NEW Pvt. Ltd.
 
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 applicationAMARAAHMED7
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Webservices in SalesForce (part 1)
Webservices in SalesForce (part 1)Mindfire Solutions
 
Java servlets
Java servletsJava servlets
Java servletsyuvarani p
 
Xml web services
Xml web servicesXml web services
Xml web servicesRaghu nath
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 

Ähnlich wie 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
 

Mehr von Binu Bhasuran

Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast trackBinu Bhasuran
 
Microsoft Azure solutions - Whitepaper
Microsoft Azure solutions - WhitepaperMicrosoft Azure solutions - Whitepaper
Microsoft Azure solutions - WhitepaperBinu Bhasuran
 
Microsoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkMicrosoft Managed Extensibility Framework
Microsoft Managed Extensibility FrameworkBinu Bhasuran
 
Restful Services With WFC
Restful Services With WFCRestful Services With WFC
Restful Services With WFCBinu Bhasuran
 
Design patterns
Design patternsDesign patterns
Design patternsBinu Bhasuran
 
Wcf development
Wcf developmentWcf development
Wcf developmentBinu Bhasuran
 
.Net platform an understanding
.Net platform an understanding.Net platform an understanding
.Net platform an understandingBinu Bhasuran
 
Moving from webservices to wcf services
Moving from webservices to wcf servicesMoving from webservices to wcf services
Moving from webservices to wcf servicesBinu Bhasuran
 
Model view view model
Model view view modelModel view view model
Model view view modelBinu Bhasuran
 
Beginning with wcf service
Beginning with wcf serviceBeginning with wcf service
Beginning with wcf serviceBinu 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
 

Mehr von 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#
 

KĂŒrzlich hochgeladen

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...gurkirankumar98700
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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 slidevu2urc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 

KĂŒrzlich hochgeladen (20)

Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍾 8923113531 🎰 Avail...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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.

Hinweis der Redaktion

  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.