SlideShare a Scribd company logo
1 of 39
Contents
 What & Why ASP.NET Web API
 A look at Rest & Soap
 Basic Web API Structure
 Web API Routing & Actions
 Validation
 Odata
 Content Negotiation
 Http Client
ASP.NET Web API
 ASP.NET Web API is a framework for building http
based services in top of .net framework.
 WCF  Care about transport flexibility.
 WebAPI  Care about HTTP
Build Richer Apps
Reach More Clients
 Reach more clients
 Client appropriate format
 Embrace http
 Use http as an application protocol
 Amazon has both Rest and Soap based services
and 85% of the usage is Rest based.
 SOAP
 A specification
 Rest
 A set of architectural principal
 Resource Oriented Architecture
 Resources
 Their names(URIs)
 Uniform Intercace
 Asmx
 Ws*
 Wcf
 Wcf 3.5
 Wcf rest starter kit
 Wcf Rest service
 ASP.Net Web API
Web API - 1 slide
public class ValueController : ApiController
{
// GET <controller>
public string Get()
{
return "Demo result at " + DateTime.Now.ToString();
}
}
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.Routes.Add("default",
new HttpRoute("{controller}"));
}
Demo
Microsoft
/web
®
Sample Read-only Model and Controller
Microsoft
/web
®
Read-only Controller Actions to return data
Microsoft
/web
®
Routing a Web API Using Global.asax.cs
Routing and Actions
 Web API uses the HTTP method, not the URI path,
to select the action.
 To determine which action to invoke, the framework
uses a routing table.
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
 If no route matches, the client receives a 404 error.
 Custom name mapping to http actions.
[HttpGet]
public Product FindProduct(id) {}
 or can override the action name by using
the ActionName attribute.
 api/products/thumbnail/id
[HttpGet]
[ActionName("Thumbnail")]
public HttpResponseMessage
GetThumbnailImage(int id);
 To prevent a method from getting invoked as an
action, use the NonAction attribute.
// Not an action method.
[NonAction]
public string GetPrivateData() { ... }
Exception Handling
 By default, most exceptions are translated into an HTTP response
with status code 500, Internal Server Error.
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var resp = new
HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID
= {0}", id)),
}
throw new HttpResponseException(resp);
}
return item;
}
 HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Date: Thu, 09 Aug 2012 23:27:18 GMT
Content-Length: 51
{
"Message": “No product with id = 12 not found"
}
 You can customize how Web API handles exceptions by
writing an exception filter.
public class NotImplExceptionFilterAttribute :
ExceptionFilterAttribute
{
public override void
OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new
HttpResponseMessage(HttpStatusCode.NotImplemented);
}
}
}
There are several ways to register a Web API
exception filter:
 By action
 By controller
 Globally
[NotImplExceptionFilter]
GlobalConfiguration.Configuration.Filters.Add(
new
ProductStore.NotImplExceptionFilterAttribute());
Validation
 public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
[Range(0,999)]
public double Weight { get; set; }
}
 if (ModelState.IsValid)
{
return new
HttpResponseMessage(HttpStatusCode.OK);
}
else
{
return new
HttpResponseMessage(HttpStatusCode.BadReques
t);
}
 public class ModelValidationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (KeyValuePair<string, ModelState> keyValue in
actionContext.ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e =>
e.ErrorMessage);
}
actionContext.Response =
actionContext.Request.CreateResponse(HttpStatusCode.BadReq
uest, errors);
}
}
}
 HTTP/1.1 400 Bad Request
Server: ASP.NET Development Server/10.0.0.0
Date: Fri, 20 Jul 2012 21:42:18 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 239
Connection: Close
{
"product": [
"Required property 'Name' not found in JSON. Line 1, position 18."
],
"product.Name": [
"The Name field is required."
],
"product.Weight": [
"The field Weight must be between 0 and 999."
]
}
 GlobalConfiguration.Configuration.Filters.Add(new
ModelValidationFilterAttribute());
 [ModelValidationFilter]
 public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
[JsonIgnore]
public int ProductCode { get; set; } // omitted
}
 [DataContract]
public class Product
{
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal Price { get; set; }
public int ProductCode { get; set; } // omitted by
default
}
OData
http://localhost/Products?$orderby=Name
The EnableQuerySupport method enables query
options gloablly for any controller action that
returns anIQueryable type.
 To enable only for specific action/controller
[Queryable]
IQueryable<Product> Get() {}
Option Description
$filter
Filters the results, based on a Boolean
condition.
$inlinecount
Tells the server to include the total count
of matching entities in the response.
(Useful for server-side paging.)
$orderby Sorts the results.
$skip Skips the first n results.
$top Returns only the first n the results.
:
 http://localhost/odata/Products?$orderby=Category,
Price desc
[Queryable(PageSize=10)]
public IQueryable<Product> Get()
{
return products.AsQueryable();
}
[Queryable(AllowedQueryOptions=
AllowedQueryOptions.Skip |
AllowedQueryOptions.Top)]
Demo
Content Negotiation
 The process of selecting the best representation for
a given response when there are multiple
representations available.
 Accept:
 Accept-Charset:
 Accept-Language:
 Accept-Encoding:
HttpClient
 HttpClient is a modern HTTP client for ASP.NET Web
API. It provides a flexible and extensible API for
accessing all things exposed through HTTP.
 HttpClient is the main class for sending and
receiving HttpRequestMessages and
HttpResponseMessages.
 Task based pattern
 Same HttpClient instance can be used for multiple
URIs even from different domains.
Demo
Self Reading
 Authentication and Authorization
 Extensibility
 Tracing and Debugging
Thanks

More Related Content

What's hot

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
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentationBhavin Shah
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - ObjectsWebStackAcademy
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & DevelopmentAshok Pundit
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaEdureka!
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 

What's hot (20)

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
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
REST API
REST APIREST API
REST API
 
Spring Core
Spring CoreSpring Core
Spring Core
 
MVC ppt presentation
MVC ppt presentationMVC ppt presentation
MVC ppt presentation
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
REST API Design & Development
REST API Design & DevelopmentREST API Design & Development
REST API Design & Development
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
Api presentation
Api presentationApi presentation
Api presentation
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Xke spring boot
Xke spring bootXke spring boot
Xke spring boot
 

Viewers also liked

The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersKevin Hazzard
 
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
 
data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.netsubakrish
 
Data controls ppt
Data controls pptData controls ppt
Data controls pptIblesoft
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentationdimuthu22
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.NetHitesh Santani
 
Concepts of Asp.Net
Concepts of Asp.NetConcepts of Asp.Net
Concepts of Asp.Netvidyamittal
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controlsGuddu gupta
 
ASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsRandy Connolly
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1Kumar S
 

Viewers also liked (17)

The ASP.NET Web API for Beginners
The ASP.NET Web API for BeginnersThe ASP.NET Web API for Beginners
The ASP.NET Web API for Beginners
 
Nnnnnn
NnnnnnNnnnnn
Nnnnnn
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
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
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
data controls in asp.net
data controls in asp.netdata controls in asp.net
data controls in asp.net
 
Asp.net basic
Asp.net basicAsp.net basic
Asp.net basic
 
Asp.net
 Asp.net Asp.net
Asp.net
 
Data controls ppt
Data controls pptData controls ppt
Data controls ppt
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
Server Controls of ASP.Net
Server Controls of ASP.NetServer Controls of ASP.Net
Server Controls of ASP.Net
 
Concepts of Asp.Net
Concepts of Asp.NetConcepts of Asp.Net
Concepts of Asp.Net
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
 
ASP.NET 10 - Data Controls
ASP.NET 10 - Data ControlsASP.NET 10 - Data Controls
ASP.NET 10 - Data Controls
 
Web forms in ASP.net
Web forms in ASP.netWeb forms in ASP.net
Web forms in ASP.net
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 
Introduction to asp.net
Introduction to asp.netIntroduction to asp.net
Introduction to asp.net
 

Similar to ASP.NET Web API

The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIEyal Vardi
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networkingVitali Pekelis
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAravindharamanan S
 
Connecting to a Webservice.pdf
Connecting to a Webservice.pdfConnecting to a Webservice.pdf
Connecting to a Webservice.pdfShaiAlmog1
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authenticationWindowsPhoneRocks
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejugrobbiev
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Dan Wahlin
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Michael Plöd
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!DataArt
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCSunpawet Somsin
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design PatternsGodfrey Nolan
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0PhilWinstanley
 
Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core Binary Studio
 
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineGoogle Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineRoman Kirillov
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1Dipendra Shekhawat
 

Similar to ASP.NET Web API (20)

The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web APIThe Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networking
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
 
Connecting to a Webservice.pdf
Connecting to a Webservice.pdfConnecting to a Webservice.pdf
Connecting to a Webservice.pdf
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
Enterprise Guice 20090217 Bejug
Enterprise Guice 20090217 BejugEnterprise Guice 20090217 Bejug
Enterprise Guice 20090217 Bejug
 
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
Building the an End-to-End ASP.NET MVC 4, Entity Framework, HTML5, jQuery app...
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Тарас Олексин - Sculpt! Your! Tests!
Тарас Олексин  - Sculpt! Your! Tests!Тарас Олексин  - Sculpt! Your! Tests!
Тарас Олексин - Sculpt! Your! Tests!
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Wicket 6
Wicket 6Wicket 6
Wicket 6
 
Android Design Patterns
Android Design PatternsAndroid Design Patterns
Android Design Patterns
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
 
Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core Academy PRO: ASP .NET Core
Academy PRO: ASP .NET Core
 
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngineGoogle Cloud Endpoints: Building Third-Party APIs on Google AppEngine
Google Cloud Endpoints: Building Third-Party APIs on Google AppEngine
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Creating web api and consuming- part 1
Creating web api and consuming- part 1Creating web api and consuming- part 1
Creating web api and consuming- part 1
 

Recently uploaded

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

ASP.NET Web API

  • 1.
  • 2. Contents  What & Why ASP.NET Web API  A look at Rest & Soap  Basic Web API Structure  Web API Routing & Actions  Validation  Odata  Content Negotiation  Http Client
  • 3. ASP.NET Web API  ASP.NET Web API is a framework for building http based services in top of .net framework.  WCF  Care about transport flexibility.  WebAPI  Care about HTTP
  • 4. Build Richer Apps Reach More Clients
  • 5.  Reach more clients  Client appropriate format  Embrace http  Use http as an application protocol  Amazon has both Rest and Soap based services and 85% of the usage is Rest based.
  • 6.
  • 7.  SOAP  A specification  Rest  A set of architectural principal  Resource Oriented Architecture  Resources  Their names(URIs)  Uniform Intercace
  • 8.
  • 9.
  • 10.  Asmx  Ws*  Wcf  Wcf 3.5  Wcf rest starter kit  Wcf Rest service  ASP.Net Web API
  • 11. Web API - 1 slide public class ValueController : ApiController { // GET <controller> public string Get() { return "Demo result at " + DateTime.Now.ToString(); } } protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configuration.Routes.Add("default", new HttpRoute("{controller}")); }
  • 12. Demo
  • 15. Microsoft /web ® Routing a Web API Using Global.asax.cs
  • 16. Routing and Actions  Web API uses the HTTP method, not the URI path, to select the action.  To determine which action to invoke, the framework uses a routing table. routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
  • 17.  If no route matches, the client receives a 404 error.  Custom name mapping to http actions. [HttpGet] public Product FindProduct(id) {}
  • 18.  or can override the action name by using the ActionName attribute.  api/products/thumbnail/id [HttpGet] [ActionName("Thumbnail")] public HttpResponseMessage GetThumbnailImage(int id);
  • 19.  To prevent a method from getting invoked as an action, use the NonAction attribute. // Not an action method. [NonAction] public string GetPrivateData() { ... }
  • 20. Exception Handling  By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error. public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent(string.Format("No product with ID = {0}", id)), } throw new HttpResponseException(resp); } return item; }
  • 21.  HTTP/1.1 404 Not Found Content-Type: application/json; charset=utf-8 Date: Thu, 09 Aug 2012 23:27:18 GMT Content-Length: 51 { "Message": “No product with id = 12 not found" }
  • 22.  You can customize how Web API handles exceptions by writing an exception filter. public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is NotImplementedException) { context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); } } }
  • 23. There are several ways to register a Web API exception filter:  By action  By controller  Globally [NotImplExceptionFilter] GlobalConfiguration.Configuration.Filters.Add( new ProductStore.NotImplExceptionFilterAttribute());
  • 24. Validation  public class Product { public int Id { get; set; } [Required] public string Name { get; set; } public decimal Price { get; set; } [Range(0,999)] public double Weight { get; set; } }
  • 25.  if (ModelState.IsValid) { return new HttpResponseMessage(HttpStatusCode.OK); } else { return new HttpResponseMessage(HttpStatusCode.BadReques t); }
  • 26.  public class ModelValidationFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ModelState.IsValid == false) { var errors = new Dictionary<string, IEnumerable<string>>(); foreach (KeyValuePair<string, ModelState> keyValue in actionContext.ModelState) { errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage); } actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadReq uest, errors); } } }
  • 27.  HTTP/1.1 400 Bad Request Server: ASP.NET Development Server/10.0.0.0 Date: Fri, 20 Jul 2012 21:42:18 GMT Content-Type: application/json; charset=utf-8 Content-Length: 239 Connection: Close { "product": [ "Required property 'Name' not found in JSON. Line 1, position 18." ], "product.Name": [ "The Name field is required." ], "product.Weight": [ "The field Weight must be between 0 and 999." ] }
  • 29.  public class Product { public string Name { get; set; } public decimal Price { get; set; } [JsonIgnore] public int ProductCode { get; set; } // omitted }
  • 30.  [DataContract] public class Product { [DataMember] public string Name { get; set; } [DataMember] public decimal Price { get; set; } public int ProductCode { get; set; } // omitted by default }
  • 31. OData http://localhost/Products?$orderby=Name The EnableQuerySupport method enables query options gloablly for any controller action that returns anIQueryable type.  To enable only for specific action/controller [Queryable] IQueryable<Product> Get() {}
  • 32. Option Description $filter Filters the results, based on a Boolean condition. $inlinecount Tells the server to include the total count of matching entities in the response. (Useful for server-side paging.) $orderby Sorts the results. $skip Skips the first n results. $top Returns only the first n the results. :
  • 33.  http://localhost/odata/Products?$orderby=Category, Price desc [Queryable(PageSize=10)] public IQueryable<Product> Get() { return products.AsQueryable(); } [Queryable(AllowedQueryOptions= AllowedQueryOptions.Skip | AllowedQueryOptions.Top)]
  • 34. Demo
  • 35. Content Negotiation  The process of selecting the best representation for a given response when there are multiple representations available.  Accept:  Accept-Charset:  Accept-Language:  Accept-Encoding:
  • 36. HttpClient  HttpClient is a modern HTTP client for ASP.NET Web API. It provides a flexible and extensible API for accessing all things exposed through HTTP.  HttpClient is the main class for sending and receiving HttpRequestMessages and HttpResponseMessages.  Task based pattern  Same HttpClient instance can be used for multiple URIs even from different domains.
  • 37. Demo
  • 38. Self Reading  Authentication and Authorization  Extensibility  Tracing and Debugging