SlideShare une entreprise Scribd logo
1  sur  52
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.
• 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.
• 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
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
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
Here , I have defined constraints…. Integer value must not be less then 2
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 Features for Building Secure and Scalable RESTful Services

Contenu connexe

Tendances

Cache control directive
Cache control directiveCache control directive
Cache control directiveMohamed Mamoon
 
Introduction To Asp.Net Ajax
Introduction To Asp.Net AjaxIntroduction To Asp.Net Ajax
Introduction To Asp.Net AjaxJeff Blankenburg
 
Ajax control asp.net
Ajax control asp.netAjax control asp.net
Ajax control asp.netSireesh K
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performancerudib
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentChui-Wen Chiu
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.NetHitesh Santani
 
Webservices testing using SoapUI
Webservices testing using SoapUIWebservices testing using SoapUI
Webservices testing using SoapUITesting World
 
ASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server ControlsASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server ControlsRandy Connolly
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing ApproachHarshaVJoshi
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing ApproachHarshJ
 

Tendances (20)

Ajax part i
Ajax part iAjax part i
Ajax part i
 
Asp
AspAsp
Asp
 
Cache control directive
Cache control directiveCache control directive
Cache control directive
 
Servlets api overview
Servlets api overviewServlets api overview
Servlets api overview
 
Introduction To Asp.Net Ajax
Introduction To Asp.Net AjaxIntroduction To Asp.Net Ajax
Introduction To Asp.Net Ajax
 
Ajax
AjaxAjax
Ajax
 
Web Services Testing
Web Services TestingWeb Services Testing
Web Services Testing
 
Introduction to asp
Introduction to aspIntroduction to asp
Introduction to asp
 
Ajax control asp.net
Ajax control asp.netAjax control asp.net
Ajax control asp.net
 
Ch3 server controls
Ch3 server controlsCh3 server controls
Ch3 server controls
 
2310 b 06
2310 b 062310 b 06
2310 b 06
 
Ajax and ASP.NET AJAX
Ajax and ASP.NET AJAXAjax and ASP.NET AJAX
Ajax and ASP.NET AJAX
 
2310 b 17
2310 b 172310 b 17
2310 b 17
 
ASP.NET MVC Performance
ASP.NET MVC PerformanceASP.NET MVC Performance
ASP.NET MVC Performance
 
Asp.Net Ajax Component Development
Asp.Net Ajax Component DevelopmentAsp.Net Ajax Component Development
Asp.Net Ajax Component Development
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
 
Webservices testing using SoapUI
Webservices testing using SoapUIWebservices testing using SoapUI
Webservices testing using SoapUI
 
ASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server ControlsASP.NET 03 - Working With Web Server Controls
ASP.NET 03 - Working With Web Server Controls
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing Approach
 
Ajax Testing Approach
Ajax Testing ApproachAjax Testing Approach
Ajax Testing Approach
 

En vedette

Design Patterns Course
Design Patterns CourseDesign Patterns Course
Design Patterns CourseAhmed Soliman
 
The OO Design Principles
The OO Design PrinciplesThe OO Design Principles
The OO Design PrinciplesSteve Zhang
 
Owin and-katana-overview
Owin and-katana-overviewOwin and-katana-overview
Owin and-katana-overviewsonia merchant
 
ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8twMVC
 
ASP.NET Web API O to 100
ASP.NET Web API O to 100ASP.NET Web API O to 100
ASP.NET Web API O to 100Himanshu Desai
 
Moving forward with ASP.NET Core
Moving forward with ASP.NET CoreMoving forward with ASP.NET Core
Moving forward with ASP.NET CoreEnea Gabriel
 
Web api crud operations
Web api crud operationsWeb api crud operations
Web api crud operationsEyal Vardi
 
Community manager: gestión de comunidades virtuales AERCO - PSM
Community manager: gestión de comunidades virtuales AERCO - PSMCommunity manager: gestión de comunidades virtuales AERCO - PSM
Community manager: gestión de comunidades virtuales AERCO - PSMJuan Carlos Mejía Llano
 
Creating scalable message driven solutions akkadotnet
Creating scalable message driven solutions akkadotnetCreating scalable message driven solutions akkadotnet
Creating scalable message driven solutions akkadotnetDavid Hoerster
 
Community Manager y Herramientas de Marketing 2.0
Community Manager y Herramientas de Marketing 2.0Community Manager y Herramientas de Marketing 2.0
Community Manager y Herramientas de Marketing 2.0Jayguer Vásquez
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web ServicesAngelin R
 
Plantilla para crear publicaciones facebook
Plantilla para crear publicaciones facebookPlantilla para crear publicaciones facebook
Plantilla para crear publicaciones facebookalixcecilia
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
MVC Seminar Presantation
MVC Seminar PresantationMVC Seminar Presantation
MVC Seminar PresantationAbhishek Yadav
 

En vedette (20)

Design Patterns Course
Design Patterns CourseDesign Patterns Course
Design Patterns Course
 
ASP.NET MVC Web API
ASP.NET MVC Web APIASP.NET MVC Web API
ASP.NET MVC Web API
 
The OO Design Principles
The OO Design PrinciplesThe OO Design Principles
The OO Design Principles
 
Owin and-katana-overview
Owin and-katana-overviewOwin and-katana-overview
Owin and-katana-overview
 
ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8ASP.NET MVC Web API -twMVC#8
ASP.NET MVC Web API -twMVC#8
 
Owin e katana
Owin e katanaOwin e katana
Owin e katana
 
The Future of ASP.NET
The Future of ASP.NETThe Future of ASP.NET
The Future of ASP.NET
 
ASP.NET Web API O to 100
ASP.NET Web API O to 100ASP.NET Web API O to 100
ASP.NET Web API O to 100
 
Moving forward with ASP.NET Core
Moving forward with ASP.NET CoreMoving forward with ASP.NET Core
Moving forward with ASP.NET Core
 
End to End Security with MVC and Web API
End to End Security with MVC and Web APIEnd to End Security with MVC and Web API
End to End Security with MVC and Web API
 
Web api crud operations
Web api crud operationsWeb api crud operations
Web api crud operations
 
Community manager: gestión de comunidades virtuales AERCO - PSM
Community manager: gestión de comunidades virtuales AERCO - PSMCommunity manager: gestión de comunidades virtuales AERCO - PSM
Community manager: gestión de comunidades virtuales AERCO - PSM
 
Creating scalable message driven solutions akkadotnet
Creating scalable message driven solutions akkadotnetCreating scalable message driven solutions akkadotnet
Creating scalable message driven solutions akkadotnet
 
Community Manager y Herramientas de Marketing 2.0
Community Manager y Herramientas de Marketing 2.0Community Manager y Herramientas de Marketing 2.0
Community Manager y Herramientas de Marketing 2.0
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
 
Plantilla para crear publicaciones facebook
Plantilla para crear publicaciones facebookPlantilla para crear publicaciones facebook
Plantilla para crear publicaciones facebook
 
Middlewares ASP.NET
Middlewares ASP.NETMiddlewares ASP.NET
Middlewares ASP.NET
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
MVC Seminar Presantation
MVC Seminar PresantationMVC Seminar Presantation
MVC Seminar Presantation
 

Similaire à Web API 2 Features for Building Secure and Scalable RESTful Services

Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
Overview of ASP.Net by software outsourcing company india
Overview of ASP.Net by software outsourcing company indiaOverview of ASP.Net by software outsourcing company india
Overview of ASP.Net by software outsourcing company indiaJignesh Aakoliya
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19Vivek chan
 
03 asp.net session04
03 asp.net session0403 asp.net session04
03 asp.net session04Vivek chan
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servletsAamir Sohail
 
Programming web application
Programming web applicationProgramming web application
Programming web applicationaspnet123
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2Jaliya Udagedara
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIKevin Hazzard
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Fioriela Bego
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!Commit Software Sh.p.k.
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applicationsdominion
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenVannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxalfredacavx97
 
58615764 net-and-j2 ee-web-services
58615764 net-and-j2 ee-web-services58615764 net-and-j2 ee-web-services
58615764 net-and-j2 ee-web-serviceshomeworkping3
 

Similaire à Web API 2 Features for Building Secure and Scalable RESTful Services (20)

Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Overview of ASP.Net by software outsourcing company india
Overview of ASP.Net by software outsourcing company indiaOverview of ASP.Net by software outsourcing company india
Overview of ASP.Net by software outsourcing company india
 
Web services intro.
Web services intro.Web services intro.
Web services intro.
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19
 
03 asp.net session04
03 asp.net session0403 asp.net session04
03 asp.net session04
 
Presentation on java servlets
Presentation on java servletsPresentation on java servlets
Presentation on java servlets
 
Programming web application
Programming web applicationProgramming web application
Programming web application
 
ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2ASP.NET MVC 5 and SignalR 2
ASP.NET MVC 5 and SignalR 2
 
Enjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web APIEnjoying the Move from WCF to the Web API
Enjoying the Move from WCF to the Web API
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!ASP.NET - Building Web Application..in the right way!
ASP.NET - Building Web Application..in the right way!
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
 
06 web api
06 web api06 web api
06 web api
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
Node JS
Node JSNode JS
Node JS
 
58615764 net-and-j2 ee-web-services
58615764 net-and-j2 ee-web-services58615764 net-and-j2 ee-web-services
58615764 net-and-j2 ee-web-services
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
 

Plus de Krunal Trivedi

Certifications for Azure Developers
Certifications for Azure DevelopersCertifications for Azure Developers
Certifications for Azure DevelopersKrunal Trivedi
 
Azure Functions - Serverless Computing
Azure Functions - Serverless ComputingAzure Functions - Serverless Computing
Azure Functions - Serverless ComputingKrunal Trivedi
 
Azure App Service for Windows Container
Azure App Service for Windows ContainerAzure App Service for Windows Container
Azure App Service for Windows ContainerKrunal Trivedi
 
Chat application with Azure SignalR Service
Chat application with Azure SignalR ServiceChat application with Azure SignalR Service
Chat application with Azure SignalR ServiceKrunal Trivedi
 
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...Implementing enterprise cloud scenarios with Microsoft cloud services and pla...
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...Krunal Trivedi
 
High Availability in Microsoft Azure
High Availability in Microsoft AzureHigh Availability in Microsoft Azure
High Availability in Microsoft AzureKrunal Trivedi
 
Windows azure active directory
Windows azure active directoryWindows azure active directory
Windows azure active directoryKrunal Trivedi
 
Windows Azure Active Directory
Windows Azure Active DirectoryWindows Azure Active Directory
Windows Azure Active DirectoryKrunal Trivedi
 
Mef with meta data and lazy loading
Mef with meta data and lazy loadingMef with meta data and lazy loading
Mef with meta data and lazy loadingKrunal Trivedi
 

Plus de Krunal Trivedi (9)

Certifications for Azure Developers
Certifications for Azure DevelopersCertifications for Azure Developers
Certifications for Azure Developers
 
Azure Functions - Serverless Computing
Azure Functions - Serverless ComputingAzure Functions - Serverless Computing
Azure Functions - Serverless Computing
 
Azure App Service for Windows Container
Azure App Service for Windows ContainerAzure App Service for Windows Container
Azure App Service for Windows Container
 
Chat application with Azure SignalR Service
Chat application with Azure SignalR ServiceChat application with Azure SignalR Service
Chat application with Azure SignalR Service
 
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...Implementing enterprise cloud scenarios with Microsoft cloud services and pla...
Implementing enterprise cloud scenarios with Microsoft cloud services and pla...
 
High Availability in Microsoft Azure
High Availability in Microsoft AzureHigh Availability in Microsoft Azure
High Availability in Microsoft Azure
 
Windows azure active directory
Windows azure active directoryWindows azure active directory
Windows azure active directory
 
Windows Azure Active Directory
Windows Azure Active DirectoryWindows Azure Active Directory
Windows Azure Active Directory
 
Mef with meta data and lazy loading
Mef with meta data and lazy loadingMef with meta data and lazy loading
Mef with meta data and lazy loading
 

Dernier

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Dernier (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 

Web API 2 Features for Building Secure and Scalable RESTful Services

  • 1. Web API 2 With MVC 5 KRUNAL TRIVEDI Microsoft Certified Trainer Email : it.ktrivedi@gmail.com 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.
  • 4.
  • 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.
  • 7.
  • 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
  • 19.
  • 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
  • 34.
  • 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
  • 46.
  • 47.
  • 48. Here , I have defined constraints…. Integer value must not be less then 2
  • 49.
  • 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