SlideShare a Scribd company logo
Web API 2 With MVC 5
KRUNAL TRIVEDI
Microsoft Certified Trainer
Email : it.ktrivedi@gmail.com
www.iamkrunaltrivedi.com
about.me/TrainerKrunal
Tweet : @TrainerKrunal
Web API 2 Introduces :
• Attribute Routing along with Convention-based routing
• IHttpActionResult
• CORS : Cross Origin Resource Sharing
• Authenticated Web API
IHttpActionResult
• IHttpActionResult interface defines a command that asynchronously
creates an HttpResponseMessage.
• IHttpActionResult interface contains ExecuteAsync() method which
creates an HttpResponseMessage asynchronously.
Web api 2 With MVC 5 With TrainerKrunal
• A Web API controller action can return any of the following
• Void
• HttpResponseMessage
• IHttpActionResult
• Some other type
IHttpActionResult
• The IHttpActionResult interface introduced in Web API 2.
• It defines HttpResponseMessage factory.
• It contains single method , ExecuteAsync , which asynchronously creates an
HttpResponseMessage instance.
Web api 2 With MVC 5 With TrainerKrunal
• If a controller action returns an IHttpActionResult , Web API calls the
ExecuteAsync method to create an HttpResponseMessage.
• Then it converts the HttpResponseMessage into an HTTP response message.
CORS : Cross Origin Resource Sharing
• CORS allows JavaScript in the browser to call an API on the different domain.
• Cross-Origin Resource Sharing is a specification that enables truly open access
across domain-boundaries.
• If you serve public content , please consider using CORS to open it up for
universal JavaScript/browser access.
• It calls an API on the different server somewhere different from it’s origin.
• For you , cross domain call is blocked by browser by default and disallowed for
the security risk.
• But , it is extremely useful if we able to do this.
• If other server allows it browser can call to that server.
• CORS defines a way in which the browser and the server can interact to
determine whether or not to allow the cross-origin request.
• The CORS standard works by adding new HTTP headers which allow servers to
serve resources to permitted origin domains.
• Browsers supports this headers and respect the restrictions they establish.
“CORS can be used as a modern alternative to
the JSONP pattern”
• While JSONP supports only the GET request method.
• CORS also supports other types of HTTP requests.
• Using CORS enables a web programmer to use regular XMLHttpRequest, which
supports better error handling than JSONP.
• JSONP can cause Cross-site-scripting issues where the external site is
compromised , CORS allows websites to manually parse responses to ensure
security.
How CORS work
• To initiate a cross-origin request , a browser sends the request with an Origin
HTTP Header.
• The value of this header is the domain that served the page.
• For example , suppose a page from http://www.iamkrunaltrivedi.com attempts to
access a user’s data in http://www.online-city-directory.com
• If the user’s browser implements CORS , the following request header would be
sent to online-city-directory.com
Origin : http://www.iamkrunaltrivedi.com
• If http://www.online-city-directory.com allows the request , it sends an Access-
Control-Allow-Origin (ACAO) header in its response.
• The value of the header indicates what origin sites are allowed.
• For example , a response to the previous request could contain the following :
Access-Control-Allow-Origin : http://www.iamkrunaltrivedi.com
• If the server does not allow the Cross-origin request , the browser will deliver an
error to http://www.iamkrunaltrivedi.com page instead of the
http://www.online-city-directory.com response.
• To allow access from all domains , a server can send the following response
header :
Access-Control-Allow-Origin : *
Demo
Web API2 With MVC 5
Create New ASP.NET Web Application
Select Web API Template with MVC
Right Click on ModelAdd New ClassCustomer.cs
Web api 2 With MVC 5 With TrainerKrunal
Right Click on Controller  Add Controller
Select Web API 2 Empty Controller
Name it CustomerController
CustomerController
Right Click on SolutionAdd New ProjectASP.NET Web Application
Select Empty Web Application Template
Right Click on WebAPIConsumer ProjectAdd New ItemHTML
PageCustomerPage.html
Go To Quick Launch and Open Manage NuGet Packages
Select jQuery Package and Install
After installation of jQuery we will get Scripts directory along with jQuery files
Create CustomerPage.cshtml page as shown below
Right Click on CustomerPage.html pageView In BrowserClick on Get Customers
buttonYou can see XMLHttpRequest cannot load , No Access-Control-Allow-Origin
header is present on the requested resource.
• Now , to Enable CORS we need following Dlls
• System.Web.Cors.dll
• System.Web.Http.Cors.dll
• Add reference of this dlls….
Again , Go Back to KTWebAPI2Demo project , our source project , Open Package
Manager Console and Search for CORS , install ASP.NET Web API Cors-Origin
Web api 2 With MVC 5 With TrainerKrunal
OR OPTIONALLY
Open WebApiConfig.cs and write down below code
Now, Set your WebAPIConsumer Project as start up project , Run your applicationClick on buttonyou can
see your getting data.To Check open Developes Tools and check the headers..
Getting a Customer By Id
• To get a customer by ID, send an HTTP GET request to
"/api/customer/id", where id is the CustomerId. Add the following
code to the script block
Modify your CustomerPage.html as shown below
Here , we are adding a label , a textbox and a button .
OnClick of button we are calling FindDetails() function which we will create next.
Create JavaScript function as shown below
Final , page looks a like
Here , you can see the Final desired output.
Again observe the URL…we are accessing the data of web application hosted on port
1436 from the Web Application hosted on port 1654…Thanks to CORS
Attribute Routing
Open CustomerControllerModify your GetCustomerId function….
Here we are using [Route] attribute to define the custom route.
We also mention that CustomerId parameter must have an integer value.
Open WebApiConfig.cs and make sure you have MapHttpAttributeRoutes method
defined
Web api 2 With MVC 5 With TrainerKrunal
Web api 2 With MVC 5 With TrainerKrunal
Here , I have defined constraints…. Integer value must not be less then 2
Web api 2 With MVC 5 With TrainerKrunal
We can also define below constraints…
IHttpActionResult
• IHttpActionResult is now supported in Web API 2.
• Now , same as your MVC ActionResult ,which has ViewResult ,
RedirectToActionResult ,now in Web API 2 IHttpActionResult return type also
return multiple types like OKResult , NotFoundResult , ConflictResult ,
BadRequestResult etc..
• IHttpActionResult simplifies unit testing process.
• It contains single method , ExecuteAsync , which asynchronously creates an
HttpResponseMessage instance
Web api 2 With MVC 5 With TrainerKrunal

More Related Content

PPTX
MVC 3-RAZOR Validation
PPT
Wcf routing kt
PPT
ASP.NET Session 10
PPTX
Introduction ASP
PPT
Active server pages
PPTX
Web Hacking Series Part 1
PPT
SOAP-UI The Web service Testing
PPTX
Active server pages
MVC 3-RAZOR Validation
Wcf routing kt
ASP.NET Session 10
Introduction ASP
Active server pages
Web Hacking Series Part 1
SOAP-UI The Web service Testing
Active server pages

What's hot (20)

PPSX
Ajax part i
PPTX
Cache control directive
PPTX
Servlets api overview
PPT
Introduction To Asp.Net Ajax
PPTX
Web Services Testing
PPTX
Introduction to asp
PPTX
Ajax control asp.net
PPTX
Ch3 server controls
PPT
2310 b 06
PPTX
Ajax and ASP.NET AJAX
PPT
2310 b 17
PPTX
ASP.NET MVC Performance
PPT
Asp.Net Ajax Component Development
PPT
Server Controls of ASP.Net
PPT
Webservices testing using SoapUI
PPT
ASP.NET 03 - Working With Web Server Controls
PPT
Ajax Testing Approach
PPT
Ajax Testing Approach
Ajax part i
Cache control directive
Servlets api overview
Introduction To Asp.Net Ajax
Web Services Testing
Introduction to asp
Ajax control asp.net
Ch3 server controls
2310 b 06
Ajax and ASP.NET AJAX
2310 b 17
ASP.NET MVC Performance
Asp.Net Ajax Component Development
Server Controls of ASP.Net
Webservices testing using SoapUI
ASP.NET 03 - Working With Web Server Controls
Ajax Testing Approach
Ajax Testing Approach
Ad

Viewers also liked (20)

KEY
Design Patterns Course
PPTX
ASP.NET MVC Web API
PPT
The OO Design Principles
PPTX
Owin and-katana-overview
PDF
ASP.NET MVC Web API -twMVC#8
PPTX
Owin e katana
PPTX
ASP.NET Web API O to 100
PPTX
Moving forward with ASP.NET Core
PPTX
End to End Security with MVC and Web API
PPTX
Web api crud operations
PDF
Community manager: gestión de comunidades virtuales AERCO - PSM
PPTX
Creating scalable message driven solutions akkadotnet
PDF
Community Manager y Herramientas de Marketing 2.0
PDF
Restful Web Services
PPTX
Plantilla para crear publicaciones facebook
PPTX
Middlewares ASP.NET
PPTX
ASP.NET Mvc 4 web api
PPTX
Asp.Net MVC Intro
PDF
MVC Seminar Presantation
Design Patterns Course
ASP.NET MVC Web API
The OO Design Principles
Owin and-katana-overview
ASP.NET MVC Web API -twMVC#8
Owin e katana
ASP.NET Web API O to 100
Moving forward with ASP.NET Core
End to End Security with MVC and Web API
Web api crud operations
Community manager: gestión de comunidades virtuales AERCO - PSM
Creating scalable message driven solutions akkadotnet
Community Manager y Herramientas de Marketing 2.0
Restful Web Services
Plantilla para crear publicaciones facebook
Middlewares ASP.NET
ASP.NET Mvc 4 web api
Asp.Net MVC Intro
MVC Seminar Presantation
Ad

Similar to Web api 2 With MVC 5 With TrainerKrunal (20)

PDF
Web Api 2.X - Lattanzi
PPTX
Codemotion Rome 2014
PDF
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
PDF
What Is Cross-Origin Resource Sharing in Web Development.pdf
PPTX
Web Security - Cookies, Domains and CORS
PPTX
CakeFest 2013 - A-Z REST APIs
PPTX
CakeFest 2013 - A-Z REST APIs
PPTX
Improving Perceived Page Performance with ASP.NET Web API and AJAX
PPTX
Rest WebAPI with OData
PDF
Cross site calls with javascript - the right way with CORS
PPTX
Asp.net web api
PDF
ASP.NET Web API Interview Questions By Scholarhat
PPTX
Building-Robust-APIs-ASPNET-Web-API-and-RESTful-Patterns.pptx
PPTX
Switch to Backend 2023 | Day 1 Part 1
PPTX
Web API or WCF - An Architectural Comparison
PPTX
06 web api
PDF
Cross-domain requests with CORS
PPTX
CORS - Enable Alfresco for CORS
PDF
Cors michael
Web Api 2.X - Lattanzi
Codemotion Rome 2014
WebCamp: Developer Day: Web Security: Cookies, Domains and CORS - Юрий Чайков...
What Is Cross-Origin Resource Sharing in Web Development.pdf
Web Security - Cookies, Domains and CORS
CakeFest 2013 - A-Z REST APIs
CakeFest 2013 - A-Z REST APIs
Improving Perceived Page Performance with ASP.NET Web API and AJAX
Rest WebAPI with OData
Cross site calls with javascript - the right way with CORS
Asp.net web api
ASP.NET Web API Interview Questions By Scholarhat
Building-Robust-APIs-ASPNET-Web-API-and-RESTful-Patterns.pptx
Switch to Backend 2023 | Day 1 Part 1
Web API or WCF - An Architectural Comparison
06 web api
Cross-domain requests with CORS
CORS - Enable Alfresco for CORS
Cors michael

More from Krunal Trivedi (9)

PPTX
Certifications for Azure Developers
PPTX
Azure Functions - Serverless Computing
PPTX
Azure App Service for Windows Container
PPTX
Chat application with Azure SignalR Service
PPTX
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...
PPTX
High Availability in Microsoft Azure
PPTX
Windows azure active directory
PPTX
Windows Azure Active Directory
PPT
Mef with meta data and lazy loading
Certifications for Azure Developers
Azure Functions - Serverless Computing
Azure App Service for Windows Container
Chat application with Azure SignalR Service
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...
High Availability in Microsoft Azure
Windows azure active directory
Windows Azure Active Directory
Mef with meta data and lazy loading

Recently uploaded (20)

PPTX
ai tools demonstartion for schools and inter college
PPTX
Transform Your Business with a Software ERP System
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Introduction to Artificial Intelligence
PDF
Digital Strategies for Manufacturing Companies
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
top salesforce developer skills in 2025.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
System and Network Administraation Chapter 3
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
ai tools demonstartion for schools and inter college
Transform Your Business with a Software ERP System
2025 Textile ERP Trends: SAP, Odoo & Oracle
CHAPTER 2 - PM Management and IT Context
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PTS Company Brochure 2025 (1).pdf.......
How to Migrate SBCGlobal Email to Yahoo Easily
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Introduction to Artificial Intelligence
Digital Strategies for Manufacturing Companies
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
VVF-Customer-Presentation2025-Ver1.9.pptx
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Design an Analysis of Algorithms II-SECS-1021-03
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
top salesforce developer skills in 2025.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Operating system designcfffgfgggggggvggggggggg
System and Network Administraation Chapter 3
Wondershare Filmora 15 Crack With Activation Key [2025

Web api 2 With MVC 5 With TrainerKrunal

  • 1. Web API 2 With MVC 5 KRUNAL TRIVEDI Microsoft Certified Trainer Email : [email protected] www.iamkrunaltrivedi.com about.me/TrainerKrunal Tweet : @TrainerKrunal
  • 2. Web API 2 Introduces : • Attribute Routing along with Convention-based routing • IHttpActionResult • CORS : Cross Origin Resource Sharing • Authenticated Web API
  • 3. IHttpActionResult • IHttpActionResult interface defines a command that asynchronously creates an HttpResponseMessage. • IHttpActionResult interface contains ExecuteAsync() method which creates an HttpResponseMessage asynchronously.
  • 5. • A Web API controller action can return any of the following • Void • HttpResponseMessage • IHttpActionResult • Some other type
  • 6. IHttpActionResult • The IHttpActionResult interface introduced in Web API 2. • It defines HttpResponseMessage factory. • It contains single method , ExecuteAsync , which asynchronously creates an HttpResponseMessage instance.
  • 8. • If a controller action returns an IHttpActionResult , Web API calls the ExecuteAsync method to create an HttpResponseMessage. • Then it converts the HttpResponseMessage into an HTTP response message.
  • 9. CORS : Cross Origin Resource Sharing • CORS allows JavaScript in the browser to call an API on the different domain. • Cross-Origin Resource Sharing is a specification that enables truly open access across domain-boundaries. • If you serve public content , please consider using CORS to open it up for universal JavaScript/browser access. • It calls an API on the different server somewhere different from it’s origin. • For you , cross domain call is blocked by browser by default and disallowed for the security risk. • But , it is extremely useful if we able to do this. • If other server allows it browser can call to that server.
  • 10. • CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. • The CORS standard works by adding new HTTP headers which allow servers to serve resources to permitted origin domains. • Browsers supports this headers and respect the restrictions they establish.
  • 11. “CORS can be used as a modern alternative to the JSONP pattern” • While JSONP supports only the GET request method. • CORS also supports other types of HTTP requests. • Using CORS enables a web programmer to use regular XMLHttpRequest, which supports better error handling than JSONP. • JSONP can cause Cross-site-scripting issues where the external site is compromised , CORS allows websites to manually parse responses to ensure security.
  • 12. How CORS work • To initiate a cross-origin request , a browser sends the request with an Origin HTTP Header. • The value of this header is the domain that served the page. • For example , suppose a page from http://www.iamkrunaltrivedi.com attempts to access a user’s data in http://www.online-city-directory.com • If the user’s browser implements CORS , the following request header would be sent to online-city-directory.com Origin : http://www.iamkrunaltrivedi.com
  • 13. • If http://www.online-city-directory.com allows the request , it sends an Access- Control-Allow-Origin (ACAO) header in its response. • The value of the header indicates what origin sites are allowed. • For example , a response to the previous request could contain the following : Access-Control-Allow-Origin : http://www.iamkrunaltrivedi.com
  • 14. • If the server does not allow the Cross-origin request , the browser will deliver an error to http://www.iamkrunaltrivedi.com page instead of the http://www.online-city-directory.com response. • To allow access from all domains , a server can send the following response header : Access-Control-Allow-Origin : *
  • 16. Create New ASP.NET Web Application
  • 17. Select Web API Template with MVC
  • 18. Right Click on ModelAdd New ClassCustomer.cs
  • 20. Right Click on Controller  Add Controller
  • 21. Select Web API 2 Empty Controller
  • 24. Right Click on SolutionAdd New ProjectASP.NET Web Application
  • 25. Select Empty Web Application Template
  • 26. Right Click on WebAPIConsumer ProjectAdd New ItemHTML PageCustomerPage.html
  • 27. Go To Quick Launch and Open Manage NuGet Packages
  • 28. Select jQuery Package and Install
  • 29. After installation of jQuery we will get Scripts directory along with jQuery files
  • 31. Right Click on CustomerPage.html pageView In BrowserClick on Get Customers buttonYou can see XMLHttpRequest cannot load , No Access-Control-Allow-Origin header is present on the requested resource.
  • 32. • Now , to Enable CORS we need following Dlls • System.Web.Cors.dll • System.Web.Http.Cors.dll • Add reference of this dlls….
  • 33. Again , Go Back to KTWebAPI2Demo project , our source project , Open Package Manager Console and Search for CORS , install ASP.NET Web API Cors-Origin
  • 36. Open WebApiConfig.cs and write down below code
  • 37. Now, Set your WebAPIConsumer Project as start up project , Run your applicationClick on buttonyou can see your getting data.To Check open Developes Tools and check the headers..
  • 38. Getting a Customer By Id • To get a customer by ID, send an HTTP GET request to "/api/customer/id", where id is the CustomerId. Add the following code to the script block
  • 39. Modify your CustomerPage.html as shown below Here , we are adding a label , a textbox and a button . OnClick of button we are calling FindDetails() function which we will create next.
  • 40. Create JavaScript function as shown below
  • 41. Final , page looks a like
  • 42. Here , you can see the Final desired output. Again observe the URL…we are accessing the data of web application hosted on port 1436 from the Web Application hosted on port 1654…Thanks to CORS
  • 44. Open CustomerControllerModify your GetCustomerId function…. Here we are using [Route] attribute to define the custom route. We also mention that CustomerId parameter must have an integer value.
  • 45. Open WebApiConfig.cs and make sure you have MapHttpAttributeRoutes method defined
  • 48. Here , I have defined constraints…. Integer value must not be less then 2
  • 50. We can also define below constraints…
  • 51. IHttpActionResult • IHttpActionResult is now supported in Web API 2. • Now , same as your MVC ActionResult ,which has ViewResult , RedirectToActionResult ,now in Web API 2 IHttpActionResult return type also return multiple types like OKResult , NotFoundResult , ConflictResult , BadRequestResult etc.. • IHttpActionResult simplifies unit testing process. • It contains single method , ExecuteAsync , which asynchronously creates an HttpResponseMessage instance