Asp.net web api extensibility

2,831
-1

Published on

Asp.net web api extensibility

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,831
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide
  • http://www.asp.net/web-api/overview/extensibility/configuring-aspnet-web-api
  • The IControllerConfiguration.Initialize method takes two parameters:An HttpControllerSettings objectAn HttpControllerDescriptor objectThe HttpControllerDescriptor contains a description of the controller, which you can examine for informational purposes (say, to distinguish between two controllers).Use the HttpControllerSettings object to configure the controller. This object contains the subset of configuration parameters that you can override on a per-controller basis. The previous example modified the formatter collection and replaced the IHttpActionSelector service. Any settings that you don't change will default to the globalHttpConfiguration object.
  • Asp.net web api extensibility

    1. 1. ASP.NET Web APIExtensibility Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog: www.eVardi.com
    2. 2. Expert Days 2012 © 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    3. 3. Agenda© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    4. 4. Web API Configuration© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    5. 5. Configuring ASP.NET Web API  Global Configuration Settings (ASP.NET Hosting)  Global Configuration Settings (Self-Hosting)  Services  Per-Controller Configuration© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    6. 6. Global Configuration Settings (ASP.NET Hosting)  Stored in the GlobalConfiguration object, which is contains a singleton HttpConfiguration instance.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    7. 7. HttpConfiguration Member Description DependencyResolver Enables dependency injection for controllers. Filters Action filters. Formatters Media-type formatters. Specifies whether the server should include error details, such as IncludeErrorDetailPolicy exception messages and stack traces, in HTTP response messages. Initializer A function that performs final initialization of the HttpConfiguration. MessageHandlers HTTP message handlers. ParameterBindingRules A collection of rules for binding parameters on controller actions. Properties A generic property bag. Routes The collection of routes Services The collection of services.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    8. 8. WebApiConfig  The call to WebApiConfig.Register configures Web API. The definition for the WebApiConfig class is located in the App_Start directory.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    9. 9. Global Configuration Settings (Self-Hosting)  If you self-host Web API, the configuration settings are stored in the HttpSelfHostConfiguration class, which derives from HttpConfiguration. var config = new HttpSelfHostConfiguration("http://localhost:8080"); // Add a route config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // Add a media-type formatter config.Formatters.Add(new MyFormatter());© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    10. 10. Services  The HttpConfiguration.Services collection contains a set of global services that Web API uses to perform various tasks.  Controller selection (IHttpControllerSelector)  Content negotiation (IContentNegotiator)  IActionValueBinder  IApiExplorer  IAssembliesResolver  IBodyModelValidator  IDocumentationProvider  IHttpActionInvoker  IHttpControllerTypeResolver  ITraceManager & ITraceWriter  …© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    11. 11. Per-Controller Configuration  You can override per controller  Media-type formatters  Parameter binding rules  Services public class ControllerConfigAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings settings, HttpControllerDescriptor descriptor) { // Remove the JSON formatter. var jsonFormatter = settings.Formatters.JsonFormatter; settings.Formatters.Remove(jsonFormatter); // Add a custom media-type formatter. settings.Formatters.Add(new MyFormatter()); // Add a custom action selector. settings.Services.Replace(typeof(IHttpActionSelector), new MyActionSelector()); } }© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    12. 12. Routing© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    13. 13. Routing Tables routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } constraints: new { id = @"d+" } ); Action HTTP method Relative URI Get a list of all products GET /api/products Get a product by ID GET /api/products/id Get a product by category GET /api/products?category=1© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    14. 14. Selecting a Controller  Controller selection is handled by the IHttpControllerSelector.SelectController method.  This method takes an HttpRequestMessage instance and returns an HttpControllerDescriptor.  The default implementation is provided by the DefaultHttpControllerSelector class. 1. Look in the route dictionary for the key "controller". 2. Take the value for this key and append the string "Controller" to get the controller type name. 3. Look for a Web API controller with this type name.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    15. 15. Selecting a Controller  For step 3, DefaultHttpControllerSelector uses the IHttpControllerTypeResolver interface to get the list of Web API controller types.  The default implementation of IHttpControllerTypeResolver returns all public classes that:  Implement IHttpController,  Not abstract  Have a name that ends in "Controller".© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    16. 16. Selecting a Controller© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    17. 17. Selecting a Controller© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    18. 18. Action Selection  Action selection done by calling the IHttpActionSelector.SelectAction method.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    19. 19. Action Selection  The default implementation is provided by the ApiControllerActionSelector class. To select an action, it looks at the following:  The HTTP method of the request.  The "{action}" placeholder in the route template, if present.  The parameters of the actions on the controller.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    20. 20. Action Selection Algorithm 1. Create a list of all actions on the controller that match the HTTP request method. 2. If the route dictionary has an "action" entry, remove actions whose name does not match this value. 3. Try to match action parameters to the URI, as follows: 1. For each action, get a list of the parameters that are a simple type, where the binding gets the parameter from the URI. Exclude optional parameters. 2. From this list, try to find a match for each parameter name, either in the route dictionary or in the URI query string. Matches are case insensitive and do not depend on the parameter order. 3. Select an action where every parameter in the list has a match in the URI. 4. If more that one action meets these criteria, pick the one with the most parameter matches. 4. Ignore actions with the [NonAction] attribute.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    21. 21. Action Selection© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    22. 22. HTTP Message Handlers© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    23. 23. HTTP Message Handlers  HttpRequestMessage represents the HTTP request.  HttpResponseMessage represents the HTTP response.  HttpMessageHandler objects process the request and response© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    24. 24. Client© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    25. 25. Server  HttpServer derives from HttpMessageHandler.  The request then passes through a series of message handlers.  HttpControllerDispatcher handler uses the routing table to route the request to a Web API controller.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    26. 26. HTTP Request in Memory var config = new HttpConfiguration(); config.Routes.MapHttpRoute( "default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); HttpServer server = new HttpServer(config); // Connect client directly to server HttpClient client = new HttpClient(server); var response = client.GetAsync("http://anything/api/products").Result;© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    27. 27. Custom Message Handlers  Process the request message.  Call base.SendAsync to send the message to the inner handler. This step is asynchronous.  Process the response message and return it to the caller. Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken);© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    28. 28. Custom Response Header public class CustomHeaderHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { return base.SendAsync(request, cancellationToken) .ContinueWith( (task) => { HttpResponseMessage response = task.Result; response.Headers.Add( "X-Custom-Header", "This is my custom header."); return response; } ); } }© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    29. 29. Custom Message Handlers© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    30. 30. Formats & Model Binding© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    31. 31. Internet Media Types  A media type, also called a MIME type.  Identifies the format of a piece of data.  Describe the format of the message body.  A media type consists of two strings, a type and a subtype. For example:  text/html  image/png  application/json HTTP/1.1 200 OK Content-Length: 95267 Content-Type: image/png Accept: text/html,application/xhtml+xml© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    32. 32. Media Formatter  In Web API, the media type determines how Web API serializes and deserializes the HTTP message body.© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    33. 33. Custom Media Formatter© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    34. 34. Exceptions© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    35. 35. Exception Handling  By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.  For example, the following method returns 404, Not Found, if the id parameter is not valid. public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException( new HttpResponseMessage( HttpStatusCode.NotFound )); } return item; }© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    36. 36. Exception Filters  An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception. NotImplementedException exceptions into HTTP status code 501, Not Implemented. public class NotImplExceptionFilter : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { if (context.Exception is NotImplementedException) { context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); } } }© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il
    37. 37. Exception Filters© 2010 E4D LTD. All rights reserved. Tel: 054-5-767-300, Email: Eyal@E4D.co.il

    ×