Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

ASP.NET Mvc 4 web api

A presentation about new ASP.NET MVC 4 Web API.

  • Be the first to comment

ASP.NET Mvc 4 web api

  1. 1. ASP.NET MVC 4 Web APITiago Knoch –
  2. 2. Contents• What is an API?• Why ASP.NET MVC Web API?• HyperText Transfer Protocol• REST• JSON• Introduction to Web API• Routing Table• Error & Exception Handling• Model Validation• Odata Protocol• Media Formatters• Security• HTTPClient• What Else?• Road Map
  3. 3. What is an API?• An application programming interface (API) is a specification intended to be used as an interface by software components to communicate with each other. An API may include specifications for routines, data structures, object classes, and variables.• For the web this mean Web Services (SOAP + XML + WSDL) but in Web 2.0 we are moving away to REST Services (HTTP + XML/JSON) – Web API• Web APIs allow the combination of multiple services into new applications known as mashups.
  4. 4. • Common examples: – Facebook, Twitter, Amazon, LinkedIn...Source:
  5. 5. Why ASP.NET MVC Web Api?• Web Api – Defined in HTTP – Messages in Json/XML – RESTful – CRUD operations – Ready for Cloud
  6. 6. HyperText Transfer Protocol• The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.• HTTP functions as a request-response protocol in the client-server computing model. A web browser, for example, may be the client and an application running on a computer hosting a web site may be the server.• The client submits an HTTP request message to the server. The server, which provides resources such as HTML files and other content, or performs other functions on behalf of the client, returns a response message to the client. The response contains completion status information about the request and may also contain requested content in its message body.
  7. 7. HTTP – Example GETGET / HTTP/1.1[CRLF]Host:[CRLF] User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0)Gecko/20100101 Firefox/15.0.1[CRLF]Accept-Encoding: gzip[CRLF]Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8[CRLF]Accept-Language: en-us,en;q=0.5[CRLF] Status: HTTP/1.1 200 OK Content-Type: text/html Content-Length: 1354 Content: <HTML data>
  8. 8. HTTP – Example POST POST /somepage.php HTTP/1.1 Host: Content-Type: application/x-www-form-urlencoded Content-Length: 19 name=tiago&surname=knoch Status: HTTP/1.1 404 Not Found
  9. 9. Rest - Representational State Transfer• REST is a style of software architecture for distributed systems such as the WWW, where, virtually in all cases, the HTTP protocol is used.• Uses CRUD actions (HTTP methods) CRUD Action HTTP Method Create Post Read Get Update Put Delete Delete• Each resource is represented by an global id (URI in HTTP)• The resources are conceptually separate from the representations that are returned to the client (JSON/XML)In many ways, the World Wide Web itself, based on HTTP, can be viewed asa REST-based architecture.Despite being simple, REST is fully-featured; theres basically nothing youcan do in Web Services that cant be done with a RESTful architecture!
  10. 10. JSON• JSON, or JavaScript Object Notation, is a text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for many languages.
  11. 11. ASP.NET MVC Web API• MVC: Model -> View -> Controller• Create a Model• Create a controller
  12. 12. Routing Table• Route is defined, by default, as api/{controller}/{id} where action is defined by an HTTP method (in global.asax Application_Start method).HTTP Method URI Path ActionGET /api/products GetAllProductsGET /api/products/id GetProductByIdGET /api/products/?category=category GetProductsByCategoryPOST /api/products PostProductPUT /api/products/id PutProductDELETE /api/products/id DeleteProduct
  13. 13. Routing TableThe four main HTTP methods are mapped to CRUD operations:• GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server.• PUT updates a resource at a specified URI (idempotent).• POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message.• DELETE deletes a resource at a specified URI (idempotent).
  14. 14. Oi?!Time for some DEMO!
  15. 15. Error & Exception Handling• Response messages, errors and exceptions are translated to HTTP response status codes.• For example: – POST request should reply with HTTP status 201 (created). – DELETE request should reply with HTTP status 204 (no content).• But: – If a PUT/GET request is done with an invalid id, it should reply with HTTP status 404 (not found) – Or if a PUT request has an invalid model, it can reply with HTTP status 400 (bad request)
  16. 16. Error & Exception Handling• By default, all .NET exceptions are translated into and HTTP response with status code 500 (internal error).• It is possible to register Exception filters:
  17. 17. Model Validation• Like MVC, Web API supports Data Annotations (System.ComponentModel.DataAnnotations, .net 4.0).• If in your model there is a difference between 0 and not set, use nullable values.
  18. 18. Model Validation - Example
  19. 19. Model Validation – FilterAttribute Create a FilterAttribute Add it to Filters in Global.asax App_Start
  20. 20. Odata Protocol•• “The Open Data Protocol (OData) is a Web protocol for querying and updating data. OData does this by applying and building upon Web technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a variety of applications, services, and stores.”• In Web API we want to do something like this: /api/products?$top=3&$orderby=Name /api/products/?$filter=substringof(a, Name) eq true /api/products/?$filter=Price gt 5 /api/products/?$filter=Price gt 1 and Category eq Hardware
  21. 21. Odata Protocol • Change GET action method to return IQueryable<T> and to use Queryable attribute • Available as Nuget package (prerelease)!PM> Install-Package Microsoft.AspNet.WebApi.OData -Pre
  22. 22. DEMO!
  23. 23. Media Formatters• Web API only provides media formatters for JSON (using Json.NET library) and XML!• In HTTP, the format of message body is defined by the MIME type (media type): text/html, image/png, application/json, application/octet-stream• When the client sends an HTTP request, the Accept header tells the server wich media type it expects: Accept: text/html, application/json, application/xml; q=0.9, */*; q=0.01• Web API uses media formatters to: – Read CLR objects from an HTTP message body (HTTP requests serializes to action methods parameters), – Write CLR objects to an HTTP message body (action methods returned objects serializes to HTTP replies)• You can create your own Media Formatter to serialize-deserialize your model types!
  24. 24. Media Formatters - Example Define which http media type is supported Define which types can be deserialized
  25. 25. Media Formatters - ExampleDeserialize type to stream Define formatter in global.asax App_Start
  26. 26. Security• Support for the [Authorize] Attribute (System.Web.Http.AuthorizeAttribute)...but it only checks UserPrincipal.Identity.IsAuthenticated (Forms authentication).• For more secure options you need to implement a custom filter: – Tokens (ex, Public/Private Keys) – Oauth ( – OpenID ( – Forms Authentication (already supported by ASP.NET) – Basic Http Authentication (username/password encrypted ) – SSL• Amazon S3 REST API uses a custom HTTP scheme based on a keyed-HMAC (Hash Message Authentication Code) for authentication.• The Facebook/Twitter/Google API use OAuth for authentication and authorization.
  27. 27. Testing from a .NET client - HttpClient• HttpClient - Available in .NET 4.5 or NuGet package Microsoft.AspNet.WebApi.Client• Or use RestSharp (
  28. 28. What else?• Improved support for IoC containers• Create help pages (IApiExplorer service)• Web API Project Template in VS 2012• Scaffold controllers from Entity Framework model (like MVC)• Easy integration with Azure
  29. 29. Road Map• MVC 4 was released in ASP.NET 4.5 with Visual Studio 2012 and .NET Framework 4.5.• Check out more at
  30. 30. Questions?Tiago Knoch: