Discover. Master. Influence.
Senior Consultant at Readify
  @H_Desai
  http://himanshudesai.wordpress.com




               Discover. Master. Influence.   2
•   Getting up-to speed
•   Going Deep
•   Other Concerns
•   Lessons from the field




                    Discover. Master. Influence.
ASP.NET Web API Features

• From ASP.NET MVC        • From WCF Web API




•   Link generation       •       Server-side query composition
•   Testability           •       Create custom help pages
•   IoC integration       •       Self-host
•   VS template           •       Tracing
•   Scaffolding



                      Discover. Master. Influence.          4
• Two hosting options today
  – ASP.NET Web Application(IIS)
  – Self-host server option (console
    application, windows service, Azure worker
    Role etc)
• HttpConfiguration is the common
  denominator
• Host in memory for end-to-end testing
• Use an OWIN bridge to host on any OWIN
  compatible web server
                  Discover. Master. Influence.   5
Discover. Master. Influence.   6
Discover. Master. Influence.   7
Discover. Master. Influence.
HTTP request/response handling




     Client            Server
• Message Handlers




               Message
               Handler
                   Message
  HttpServer           Message
                    Handler                      Http
                                                           ApiController
                       Handler                Dispatcher




                         Discover. Master. Influence.             10
• Http Dispatcher
                         Invoke Action


                            Action Filters


         Model Bind


                      Authorization Filters


         Select action                         Exception filters


      Route to controller                          Formatting


          Request                      Response
                                Discover. Master. Influence.       11
• Action Filters
• Authorization Filters
• Exception Filters




                  Discover. Master. Influence.   12
Discover. Master. Influence.   13
• Simple types are taken from the URI
• Complex types come from the body
• Override using
  [FromUri],[FromBody],[ModelBinder],
  custom parameter binding




                Discover. Master. Influence.   14
• HttpRequest->.NET Type

/?id=123&name=bob
void Action(int id, string name)
// both parameters are simple types and will come from url

/?id=123&name=bob
void Action([FromUri] int id, [FromUri] string name)
// paranoid version of above.



                         Discover. Master. Influence.   15
void Action([FromBody] string name);
// explicitly read the body as a string.

/?id=123
void Action(int id, Customer c)
// id from query string, c is a complex object, comes from
body via a formatter.




                          Discover. Master. Influence.   16
void Action(Customer c1, Customer c2)
// error! multiple parameters attempting to read from the
body

void Action([FromUri] Customer c1, Customer c2) // ok, c1 is
from the URI and c2 is from the body




                         Discover. Master. Influence.   17
void Action([ModelBinder(MyCustomBinder)] SomeType c)
// Specifies a precise model binder to use to create the
parameter.

[ModelBinder(MyCustomBinder)]
public class SomeType { }

// place attribute on type declaration to apply to all
parameter instances
void Action(SomeType c)


                          Discover. Master. Influence.   18
Discover. Master. Influence.
Discover. Master. Influence.   20
Discover. Master. Influence.
•   Media Type Formatter
•   Delegating Handler
•   IOC
•   Services (e.g. Tracing)




                     Discover. Master. Influence.   22
Discover. Master. Influence.
• Built-In
  – Json
  – Xml
  – FormUrl-Encoded
  – ODataMediaType
• Custom



                Discover. Master. Influence.   24
Discover. Master. Influence.   25
Discover. Master. Influence.
Discover. Master. Influence.   27
Discover. Master. Influence.
Discover. Master. Influence.   29
Discover. Master. Influence.
Discover. Master. Influence.   33
Discover. Master. Influence.
• Demo
  – Test Controller via Http
  – Test Delegating Handlers




                    Discover. Master. Influence.   35
•   Be careful about OData Versioning (alpha right?)
•   Message Handler error handling
•   Don’t let your EF code leak out.
•   Ensure you write HTTP level tests for controller.
•   Tracing is enabled.
•   Remove Formatters you don’t need.
•   Add JSONP and CORS formatters (Not available by default)




                         Discover. Master. Influence.   36
Discover. Master. Influence.

ASP.NET Web API O to 100

Editor's Notes

  • #6 http://www.strathweb.com/2012/12/running-aspnet-web-api-with-owin-and-katana/Open Web Interface for .NETKatana is an OWIN implementation for Microsoft hosts (HttpListener, System.Web) and the Web API framework.
  • #7 1. What it is?2. Basic template (Talk about layout and basic structure Routing/Verbs/Help pages, Default Formatters, Content Negotiation) 2a (Demo-Create a basic Web API as it is from box)3. Getting Started 3a (Demo-Modify the template which was created)
  • #8 1. What it is?2. Basic template (Talk about layout and basic structure Routing/Verbs/Help pages, Default Formatters, Content Negotiation) 2a (Demo-Create a basic Web API as it is from box)3. Getting Started 3a (Demo-Modify the template which was created)
  • #13 Filters are used to handle cross cutting concernsFilter types:Action filters run before and after invoking an actionAuthorization filters run before model binding and are specifically for authorizing the userException filters handle generating responses for error cases in a centralized wayFilters can be configured globally, per controller, or per action as an attribute
  • #14 Talk about Exception Filter. Create sample filter to the pipeline and show it
  • #15 Simple types: Route data, query parametersComplex types Configured MediaTypeFormatters are used to deserialize the request body based the content type JSON, XML and form-url-encoded supported out of the box.
  • #16 http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspxIf the parameter has no attribute on it, then the decision is made purely on the parameter’s .NET type.“Simple types” uses model binding. Complex types uses the formatters. A “simple type” includes:primitives, TimeSpan, DateTime, Guid, Decimal, String, or something with a TypeConverter that converts from strings.You can use a [FromBody] attribute to specify that a parameter should be from the body.You can use a [ModelBinder] attribute on the parameter or the parameter’s type to specify that a parameter should be model bound. This attribute also lets you configure the model binder.  [FromUri] is a derived instance of [ModelBinder] that specifically configures a model binder to only look in the URI.The body can only be read once.  So if you have 2 complex types in the signature, at least one of them must have a [ModelBinder] attribute on it.Differences with MVCHere are some differences between MVC and WebAPI’s parameter binding:MVC only had model binders and no formatters. That’s because MVC would model bind over the request’s body (which it commonly expected to just be FormUrl encoded), whereas WebAPI uses a serializer over the request’s body.MVC buffered the request body, and so could easily feed it into model binding. WebAPI does not buffer the request body, and so does not model bind against the request body by default.WebAPI’s binding can be determined entirely statically based off the action signature types. For example, in WebAPI, you know statically whether a parameter will bind against the body or the query string. Whereas in MVC, the model binding system would search both body and query string.
  • #17 http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx
  • #18 http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx
  • #19 http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx
  • #21 (QueryablevsODataResult<>) Demo OData (Queryable/ODataResult) (talk about what is supported:top,skip,filter and orderby)e.g demo three types of Querying, filtering and paging
  • #25 Simple types: Route data, query parametersComplex types Configured MediaTypeFormatters are used to deserialize the request body based the content type JSON, XML and form-url-encoded supported out of the box.
  • #26 e.g. BSON Formatter
  • #28 e.g.ETagHandler
  • #34 e.gBasicAuthenticationHandler