SlideShare a Scribd company logo
ASP.NET Web API
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.
ASP.NET Web API
 SOAP
 A specification
 Rest
 A set of architectural principal
 Resource Oriented Architecture
 Resources
 Their names(URIs)
 Uniform Intercace
ASP.NET Web API
ASP.NET Web API
 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

ASP.NET Web API

  • 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.
  • 7.  SOAP  A specification  Rest  A set of architectural principal  Resource Oriented Architecture  Resources  Their names(URIs)  Uniform Intercace
  • 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