ASP.NET Web API Telerik Software Academy

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Telerik School Academy ASP.NET MVC.
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Touch and Gestures with Xamarin Forms
Telerik School Academy ASP.NET MVC.
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
(formerly ASP.NET vNext) Lean .NET stack for building modern web apps
RESTful Services with ASP.NET Web API Vladimir Georgiev Technical Trainer & Software Developer
With Mocha and Karma Telerik Academy Telerik Software Academy.
Welcome to the JSON-stores world Telerik Software Academy Databases.
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Creating Web Services with C#
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Nikolay Kostov Telerik Software Academy Senior Software Developer and Trainer
Telerik Software Academy End-to-end JavaScript Applications.
What is a Database, MySQL Specifics Trần Anh Tuấn Edit from Telerik Software Academy
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
ORM Concepts, Entity Framework (EF), DbContext
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Presentation transcript:

ASP.NET Web API Telerik Software Academy

2 Table of Contents What is ASP.NET Web API? Web API Features Demo: Default Project Template Web API Controllers Routes Demo: Create API Controller OData queries Web API Clients Demo: Consuming Web API

4 ASP.NET Web API Framework that makes it easy to build HTTP services for browsers and mobile devices Platform for building RESTful applications on the.NET Framework using ASP.NET stack

5 Data storage Data Layer (EF) ASP.NET Web API HTTP PUT, POST, DELETE JSON HTTP GET JSON Models XM L

6 Web API Features Modern HTTP programming model Access to strongly typed HTTP object model HttpClient API – same programming model Content negotiation Client and server work together to determine the right format for data Provide default support for JSON, XML and Form URL-encoded formats We can add own formats and change content negotiation strategy

7 Web API Features (2) Query composition Support automatic paging and sorting Support querying via the OData URL conventions when we return IQueryable Model binding and validation Combine HTTP data in POCO models Data validation via attributes Supports the same model binding and validation infrastructure as ASP.NET MVC

8 Web API Features (3) Routes (mapping between URIs and code) Full set of routing capabilities supported within ASP.NET (MVC) Filters Easily decorates Web API with additional validation (authorization, CORS, etc.) Testability IoC and dependency injection support Flexible hosting (IIS, Azure, self-hosting)

9 Web API Features (4) Visual Studio IDE (+templates and scaffolding) Reuse of C# knowledge (+task-based async) Custom help pages, tracing, etc.

10 ASP.NET Web API 2 Attribute routing OData improvements: $select, $expand, $batch, $value and improved extensibility Request batching Portable ASP.NET Web API Client Improved testability CORS (Cross-origin resource sharing) Authentication filters OWIN support and integration (owin.org)owin.org

13 Web API Controllers A controller is an object that handles HTTP requests All API controllers derive from ApiController By default ASP.NET Web API will map HTTP requests to specific methods called actions ActionHTTP methodRelative URIMethod Get a list of all postsGET/api/postsGet() Get a post by IDGET/api/posts/idGet(int id) Create a new postPOST/api/postsPost(PostModel value) Update a postPUT/api/posts/idPut(int id, PostModel value) Delete a postDELETE/api/posts/idDelete(int id) Get a post by categoryGET /api/posts?category=cat egory Get(string category)

14 Web RequestMatch a RouteAPI Controller Responds public class PostsController : ApiController { public string Get() public string Get() { return "Some data"; } return "Some data"; }} HTTP GET Request 12 3 Controller Name

15 Routing Routing is how ASP.NET Web API matches a URI to a controller and an action Web APIs support the full set of routing capabilities from ASP.NET (MVC) Route parameters Constraints (using regular expressions) Extensible with own conventions Attribute routing is available in version 2 Attribute routing

16 Default Route Web API also provides smart conventions by default We can create classes that implement Web APIs without having to explicitly write code HTTP Verb is mapped to an action name routes.MapHtpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}", routeTemplate: "api/{controller}/{id}", defaults: new { id = RoutesParameter.Optional }); defaults: new { id = RoutesParameter.Optional });

17 Model Binding & Formatters By default the Web API will bind incoming data to POCO (CLR) types Will look in body, header and query string ASP.NET MVC has similar model binder MediaTypeFormatters are used to bind both input and output Mapped to content types Validation attributes can also be used To go down further into the HTTP (set headers, etc.) we can use HttpRequestMessage and HttpResponseMessage

19 Return Different HTTP Code By default when everything is OK, we return HTTP status code 200 Sometimes we need to return error public HttpResponseMessage Get(int id) { if (dataExists) if (dataExists) { return Request.CreateResponse( HttpStatusCode.OK, data); return Request.CreateResponse( HttpStatusCode.OK, data); } else } else { return Request.CreateErrorResponse( HttpStatusCode.NotFound, "Item not found!"); return Request.CreateErrorResponse( HttpStatusCode.NotFound, "Item not found!"); } } } }

20 OData Query Syntax OData ( is a open specification written by Microsofthttp://odata.org Provide a standard query syntax on resources Implemented by WCF Data Services ASP.NET Web API includes automatic support for this syntax Return IQueryable instead of IEnumerable

21 OData Query Syntax To enable OData queries uncomment "config.EnableQuerySupport();" lineOData queries Then we can make OData queries like: " OptionDescription $filterFilters 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.) $orderbySorts the results. $skipSkips the first n results. $topReturns only the first n the results.

23 HttpClient Model HttpClient is a modern HTTP client for.NET Flexible and extensible API for accessing HTTP Has the same programming model as the ASP.NET Web API server side HttpRequestMessage / HttpResponseMessage Uses Task pattern from.NET 4.0 Can use async and await keywords in.NET 4.5 Installs with ASP.NET MVC 4 Can be retrieved via NuGet

24 var client = new HttpClient { BaseAddress = new Uri(" }; BaseAddress = new Uri(" };client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync("api/posts").Result; client.GetAsync("api/posts").Result; if (response.IsSuccessStatusCode) { var products = response.Content var products = response.Content.ReadAsAsync >().Result;.ReadAsAsync >().Result; foreach (var p in products) foreach (var p in products) { Console.WriteLine("{0,4} {1,-20} {2}", Console.WriteLine("{0,4} {1,-20} {2}", p.Id, p.Title, p.CreatedOn); p.Id, p.Title, p.CreatedOn); }}else Console.WriteLine("{0} ({1})", Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); (int)response.StatusCode, response.ReasonPhrase);

25 Consuming Web API from JS Web APIs can be consumed using JavaScript via HTTP AJAX request Example with jQuery: <script> $.ajax({ $.ajax({ url: '/api/posts', url: '/api/posts', success: function (posts) { success: function (posts) { var list = $('#posts'); var list = $('#posts'); for (var i = 0; i < posts.length; i++) { for (var i = 0; i < posts.length; i++) { var post = posts[i]; var post = posts[i]; list.append(' ' + post.title + ' '); list.append(' ' + post.title + ' '); } } }); });</script> Should be encoded

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране