Browser RequestIndex.htmlMVC4Traditional Request / Response for ALL rendered content and assets
Initial RequestApplication.htmMVC4RequireJS LoaderPage1 Partial.htmIndexViewModel.jsApplication.js (bootstrap)ViewModel (#...
Source: www.programmableweb.com – current APIs: 4,535
POST SimpleService.asmx/EchoString HTTP/1.1Host: localhost:1489User-Agent: Mozilla/5.0Accept: text/htmlContent-Type: appli...
POST SimpleService.asmx/EchoString HTTP/1.1Host: localhost:1489User-Agent: Mozilla/5.0Accept: text/html,application/xhtml+...
SOAP REST OData JSON POX ??
Dependency InjectionFiltersContent NegotiationTesting
Embrace HTTP
“An architectural style forbuilding distributedhypermedia systems.”
WSDL description of a web servicestypes defined in <xsd:schema>simple messagesparts of messagesinterface specificationoper...
ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
<?xml version="1.0" encoding="utf-8"?><Tasks><TaskInfo Id="1234" Status="Active" ><link rel="self" href="/api/tasks/1234" ...
ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
ASP.NET and Web Tools 2012.2 UpdateAdding a simple TestClient to ASP.NETWeb API Help Page
Serialization ValidationDeserializationResponseController /ActionRequestHTTP/1.1 200 OKContent-Length: 95267Content-Type: ...
GlobalConfiguration.Configuration.Formatters
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;json.UseDataContractJsonSerializer = true;
 "opt-out" approach "opt-in" approachpublic class Product{public string Name { get; set; }public decimal Price { get; se...
public object Get(){return new {Name = "Alice",Age = 23,Pets = new List<string> { "Fido", "Polly", "Spot" } };}public void...
var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;xml.UseXmlSerializer = true;The XmlSerializer class su...
“the process of selecting the bestrepresentation for a given response whenthere are multiple representationsavailable.”
public HttpResponseMessage GetProduct(int id){var product = new Product() { Id = id, Name = "Gizmo", Price = 1.99M };ICont...
public class ProductMD{[StringLength(50), Required]public string Name { get; set; }[Range(0, 9999)]public int Weight { get...
 [Required] [Exclude] [DataType] [Range][MetadataTypeAttribute( typeof( Employee.EmployeeMetadata ) )]public partial c...
public class ProductsController : ApiController{public HttpResponseMessage Post(Product product){if ( ModelState.IsValid )...
public class ModelValidationFilterAttribute : ActionFilterAttribute{public override void OnActionExecuting(HttpActionConte...
public class ModelValidationFilterAttribute : ActionFilterAttribute{public override void OnActionExecuting(HttpActionConte...
var config = new HttpSelfHostConfiguration("http://localhost:8080");config.Routes.MapHttpRoute("API Default", "api/{contro...
http://www.asp.net/web-api/Why I’m giving REST a restBuilding Hypermedia Web APIs with ASP.NET Web API
eyalvardi.wordpress.com
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
The Full Power of ASP.NET Web API
Upcoming SlideShare
Loading in...5
×

The Full Power of ASP.NET Web API

58,203

Published on

The Full Power of ASP.NET Web API

Published in: Technology
4 Comments
7 Likes
Statistics
Notes
No Downloads
Views
Total Views
58,203
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
127
Comments
4
Likes
7
Embeds 0
No embeds

No notes for slide
  • OSScreen ResolutionDeploymentSecurityBrowsersLoad Balance
  • Use HTTP as an Application Protocol – not a Transport Protocol
  • [ExternalReference] [Association(&quot;Sales_Customer&quot;, &quot;CustomerID&quot;, &quot;CustomerID&quot;)]
  • The Full Power of ASP.NET Web API

    1. 1. Browser RequestIndex.htmlMVC4Traditional Request / Response for ALL rendered content and assets
    2. 2. Initial RequestApplication.htmMVC4RequireJS LoaderPage1 Partial.htmIndexViewModel.jsApplication.js (bootstrap)ViewModel (#index)ViewModel (#login)Model (LoginModel)JSON RequestsHTML5 localstorageHandling disconnection
    3. 3. Source: www.programmableweb.com – current APIs: 4,535
    4. 4. POST SimpleService.asmx/EchoString HTTP/1.1Host: localhost:1489User-Agent: Mozilla/5.0Accept: text/htmlContent-Type: application/json;Content-Length: 27...XML, JSON, SOAP, AtomPub ...HeadersDataVerb URL
    5. 5. POST SimpleService.asmx/EchoString HTTP/1.1Host: localhost:1489User-Agent: Mozilla/5.0Accept: text/html,application/xhtml+xmlContent-Type: application/json;Content-Length: 27...{"Age":37,"FirstName":"Eyal","ID":"123","LastName":"Vardi“}HeadersDataVerb URL<Envelope><Header><!–- Headers --><!-- Protocols & Polices --></Header><Body><!– XML Data --></Body></Envelope>
    6. 6. SOAP REST OData JSON POX ??
    7. 7. Dependency InjectionFiltersContent NegotiationTesting
    8. 8. Embrace HTTP
    9. 9. “An architectural style forbuilding distributedhypermedia systems.”
    10. 10. WSDL description of a web servicestypes defined in <xsd:schema>simple messagesparts of messagesinterface specificationoperations of an interfaceinput messageoutput messagebinding of interface to protocols & encodingdescription of the binding for each operationservice descriptionURI and binding to port<definitions><types></types><message><part></part></message><portType><operation><input><output></operation></portType><binding><operation></binding><service><port></service></definitions>
    11. 11. ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
    12. 12. ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
    13. 13. ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
    14. 14. <?xml version="1.0" encoding="utf-8"?><Tasks><TaskInfo Id="1234" Status="Active" ><link rel="self" href="/api/tasks/1234" method="GET" /><link rel="users" href="/api/tasks/1234/users" method="GET" /><link rel="history" href="/api/tasks/1234/history" method="GET" /><link rel="complete" href="/api/tasks/1234" method="DELETE" /><link rel="update" href="/api/tasks/1234" method="PUT" /></TaskInfo><TaskInfo Id="0987" Status="Completed" ><link rel="self" href="/api/tasks/0987" method="GET" /><link rel="users" href="/api/tasks/0987/users" method="GET" /><link rel="history" href="/api/tasks/0987/history" method="GET" /><link rel="reopen" href="/api/tasks/0987" method="PUT" /></TaskInfo></Tasks>/api/tasks
    15. 15. ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish book
    16. 16. ASP.NET and Web Tools 2012.2 UpdateAdding a simple TestClient to ASP.NETWeb API Help Page
    17. 17. Serialization ValidationDeserializationResponseController /ActionRequestHTTP/1.1 200 OKContent-Length: 95267Content-Type: text/html | application/jsonAccept: text/html, application/xhtml+xml, application/xml
    18. 18. GlobalConfiguration.Configuration.Formatters
    19. 19. var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;json.UseDataContractJsonSerializer = true;
    20. 20.  "opt-out" approach "opt-in" approachpublic class Product{public string Name { get; set; }public decimal Price { get; set; }[JsonIgnore]public int ProductCode { get; set; }}[DataContract] public class Product{[DataMember] public string Name { get; set; }[DataMember] public decimal Price { get; set; }// omitted by defaultpublic int ProductCode { get; set; }}
    21. 21. public object Get(){return new {Name = "Alice",Age = 23,Pets = new List<string> { "Fido", "Polly", "Spot" } };}public void Post(JObject person){string name = person["Name"].ToString();int age = person["Age"].ToObject<int>();}
    22. 22. var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;xml.UseXmlSerializer = true;The XmlSerializer class supports a narrower set of typesthan DataContractSerializer, but gives more control over the resultingXML. Consider using XmlSerializer if you need to match an existing XMLschema.
    23. 23. “the process of selecting the bestrepresentation for a given response whenthere are multiple representationsavailable.”
    24. 24. public HttpResponseMessage GetProduct(int id){var product = new Product() { Id = id, Name = "Gizmo", Price = 1.99M };IContentNegotiator negotiator = this.Configuration.Services.GetContentNegotiator();ContentNegotiationResult result = negotiator.Negotiate( typeof(Product),this.Request, this.Configuration.Formatters);if (result == null) {var response = new HttpResponseMessage(HttpStatusCode.NotAcceptable);throw new HttpResponseException(response));}return new HttpResponseMessage(){Content = new ObjectContent<Product>(product, // What we are serializingresult.Formatter, // The media formatterresult.MediaType.MediaType // The MIME type)};}
    25. 25. public class ProductMD{[StringLength(50), Required]public string Name { get; set; }[Range(0, 9999)]public int Weight { get; set; }}
    26. 26.  [Required] [Exclude] [DataType] [Range][MetadataTypeAttribute( typeof( Employee.EmployeeMetadata ) )]public partial class Employeeinternal sealed class EmployeeMetadata[StringLength(60)][RoundtripOriginal]public string AddressLine { get; set; }}} [StringLength(60)] [RegularExpression] [AllowHtml] [Compare]
    27. 27. public class ProductsController : ApiController{public HttpResponseMessage Post(Product product){if ( ModelState.IsValid ) {// Do something with the product (not shown).return new HttpResponseMessage(HttpStatusCode.OK);}else {return new HttpResponseMessage(HttpStatusCode.BadRequest);}}}
    28. 28. public class ModelValidationFilterAttribute : ActionFilterAttribute{public override void OnActionExecuting(HttpActionContext actionContext){if (actionContext.ModelState.IsValid == false){// Return the validation errors in the response body.var errors = new Dictionary<string, IEnumerable<string>>();foreach ( var keyValue in actionContext.ModelState ){errors[keyValue.Key] =keyValue.Value.Errors.Select(e => e.ErrorMessage);}actionContext.Response =actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);}}}
    29. 29. public class ModelValidationFilterAttribute : ActionFilterAttribute{public override void OnActionExecuting(HttpActionContext actionContext){if (actionContext.ModelState.IsValid == false){// Return the validation errors in the response body.var errors = new Dictionary<string, IEnumerable<string>>();foreach ( var keyValue in actionContext.ModelState ){errors[keyValue.Key] =keyValue.Value.Errors.Select(e => e.ErrorMessage);}actionContext.Response =actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, errors);}}}protected void Application_Start() {// ...GlobalConfiguration.Configuration.Filters.Add(new ModelValidationFilterAttribute());}
    30. 30. var config = new HttpSelfHostConfiguration("http://localhost:8080");config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",new { id = RouteParameter.Optional });using (HttpSelfHostServer server = new HttpSelfHostServer(config)){server.OpenAsync().Wait();Console.ReadLine();}
    31. 31. http://www.asp.net/web-api/Why I’m giving REST a restBuilding Hypermedia Web APIs with ASP.NET Web API
    32. 32. eyalvardi.wordpress.com
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×