introducción a asp.net web api

Post on 28-May-2015

4.844 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Introducción a ASP.NET Web API

TRANSCRIPT

Introducción a

ASP.NET Web API

Rodolfo FinochiettiMVP ASP.NET/IISLagash Systemsrodolfof@lagash.com@rodolfof

Social Software Development

Web API Growth

Source: www.programmableweb.com – current APIs: 4535

+ 100% + 50% + 3400% + 235% + 71% + 86% + 46% + 63%

GET /en/html/dummy.php?name=MyName&married=not+single &male=yes HTTP/1.1Host: www.explainth.atUser-Agent: Mozilla/5.0 (Windows;en-GB; rv:1.8.0.11) Gecko/20070312 Firefox/1.5.0.11Accept: text/xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5Accept-Language: en-gb,en;q=0.5Accept-Encoding: gzip,deflateAccept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7Keep-Alive: 300Connection: keep-aliveReferer: http://www.explainth.at/en/misc/httpreq.shtml

Embrace HTTP¿Por que no WS-*?

Representational state transfer (REST)

• REST (representational state transfer) es un estilo de arquitectura de software para el intercambio de contenido en ambientes Web

• Fue introducido en el año 2000 por Roy Fielding, uno de los autores de HTTP– “Architectural Styles and the Design of Network-based

Software Architectures”

• En general el termino es utilizado para describir cualquier interfaz simple que sirva para transmitir información sobre HTTP sin una capa de mensajería adicional como SOAP, XML-RPC, Session tracking o HTTP Cookies

Premisas

• Client–server• Stateless• Cacheable• Layered system• Uniform Interface

¿Que es una Web API?

Un servicio HTTP

Diseñada para tener amplio alcance

Usa HTTP como protocolo de aplicación, no como protocolo de transporte

Arquitectura HTTP

http://www.w3.org/TR/webarch

¿Cómo funciona HTTP?

Métodos HTTP

Requerimientos de un framework para construir Web API’s

• Un modelo de programación centrado en HTTP• Mapeo sencillo de recursos a URIs• Soporte para múltiples formatos y para negociación de

contenido HTTP• Soporte para “out cross cutting concerns”• Liviano, testeable, y escalable

Alternativas para crear Web API’s

?ASP.NET MVCWCF Web HTTPWCF REST Starter KitWCF Web API

Alternativas para crear Web API’s

+ASP.NET MVCWCF Web HTTPWCF REST Starter KitWCF Web API

ASP.NET Web API

Características de ASP.NET Web API

• De ASP.NET MVC

• ASP.NET Routing• Model binding• Validation• Filters• Link generation• Testability• IoC integration• VS template• Scaffolding

• De WCF Web API

• Modern HTTP programming model• HttpClient• Task-based async• Formatting, content negotiation• Server-side query composition• Create custom help pages• Self-host• Tracing

Para implementar Web API . . .

• Derivar ApiController• Implementar las acciones– Las acciones mapean a métodos HTTP– Prefijar los nombres de los métodos como el verbo HTTP deseado –

PostComment

– Usar [Get/Post/Put/Delete] si se prefiere un nombre diferente

Ruta default en Web API

• routes.MapHttpRoute(– name: "DefaultApi",– routeTemplate: "api/{controller}/{id}",– defaults: new { id = RouteParameter.Optional }– );

Demo

Web API

Media Types• Determinan los formatos que entre cliente y

servidor• Request:• Response:

Media Types Formatters• En Web API los Media Types determinan como

se serializan y deserializan el HTTP Body• Para crear un media formatter se debe derivar

de:– MediaTypeFormatter: Asincrónico– BufferedMediaTypeFormatter: Sincrónico

Content Negotiation

• HTTP specification (RFC 2616) lo define como “the process of selecting the best representation for a given response when there are multiple representations available.”

• Utilizando– Accept:– Accept-Charset– Accept-Encoding– Accept-Language

Content Negotiation

• El HTTP Dispatcher llama a la implementación de IContentNegociator– Este objeto es el encargado de determinar la mejor

representación posible • Se llama al método Negotiate– Type del objeto a serializar– Colección de media formatters– HTTP Request

• Devuelve el formatter a usar y el media type– Si no se encuentra ningún formatter valido devuelve

null, y el cliente recibe un error HTTP 406

Demo

Media Types FormattersContent Negotiation

Validation

• La validación se corre en el modelo en cada Request– Igual que en ASP.NET MVC

• Los errores de validación se acumulan en el ModelState

• Se chequean con ModelState.IsValid• Se pueden utilizar DataAnnotations o lógica

custom de validación

OData queries

• Soporte para sintaxis de OData URL query– $top, $skip, $orderby, $filter

• Se habilita con el atributo [Queryable] y retornando IQueryable<T> desde la acción

Web API Description

• Se puede usar IApiExplorer para obtener una descripción de las Web API en runtime

• Útil para construir paginas de ayuda, clientes de test, y herramientas

IApiExplorer

IApiExplorer apiExplorer =

config.Services.GetApiExplorer();

public interface IApiExplorer{

Collection<ApiDescription> ApiDescriptions { get; }

}

Demo

ValidationWeb Api Description

OData Queries

Haciendo llamadas asincrónicas fácilmente

• Mejorar la respuesta y escalabilidad de las aplicaciones• Nuevas palabras clave “async” y “await”• Se puede usar await en casi cualquier código• Permite escribir código asincrónico que se lee como código sincrónico

Task<string> Op123Async(string s) { var tcs = new TaskCompletionSource<string>(); var state = 0; Action resume = delegate { switch (state) { case 0: Task<string> t1 = Op1Async(s); state = 1; t1.ContinueWith(resume); break; case 1: Task<string> t2 = Op2Async(t1.Result);...}

async Task<string> Op123Async(string s) { string s1 = await Op1Async(s); string s2 = await Op2Async(s1); string s3 = await Op3Async(s2); return s3;}

Asynchronous Support• Porque async en el server?

– Porque nos permite usar de manera mas eficiente los recurso del Server

• Y como funciona?– Al momento de invocar a un resource remoto, el controller le cede el

control permitiendole reutilizar el thread mientras espera la respuesta.– Cuando la llamada remota se completa, el controller es re-scheduleado

para completar su ejecución.– Menor # de threads corriendo -> aumenta la escalabilidad

• El uso de async en el servicio no se expone a browsers/clientes– http://myserver.com/products -> la misma URL puede ser

implementada en ASP.NET usando un controller sincrónico o asincronico.

Async tradicional en MVC

public class Products : AsyncController {

public void IndexAsync() {

    WebClient wc1 = new WebClient();

    AsyncManager.OutstandingOperations.Increment();

    wc1.DownloadStringCompleted += (sender, e) => {        AsyncManager.Parameters[“result"] = e.Result;        AsyncManager.OutstandingOperations.Decrement();    };

    wc1.DownloadStringAsync(new Uri("http://www.bing.com/")); }  public ActionResult IndexCompleted(string result) {    return View(); }}

Async en MVC con .NET 4.5

public class Products : Controller {

public async Task<ActionResult> IndexAsync() {

WebClient web = new WebClient();

    string result = await web.DownloadStringTaskAsync("www.bing.com/");     return View(); }}

Demo

Soporte Asincrónico

Contacto

• Mail:– rodolfof@lagash.com

• Blogs:– http://shockbyte.net

• Twitter:– @rodolfof

¡Gracias!

top related