• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
The Full Power of ASP.NET Web API
 

The Full Power of ASP.NET Web API

on

  • 8,939 views

The Full Power of ASP.NET Web API

The Full Power of ASP.NET Web API

Statistics

Views

Total Views
8,939
Views on SlideShare
8,885
Embed Views
54

Actions

Likes
3
Downloads
40
Comments
3

1 Embed 54

https://twitter.com 54

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

13 of 3 previous next Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Thanks for the slide.
    Can you point out an example for doing an XML Schema validation instead of data contract?
    Are you sure you want to
    Your message goes here
    Processing…
  • Thanks for the reference! (Giving REST a rest)
    Are you sure you want to
    Your message goes here
    Processing…
  • מצגת מעולה !!!
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • OSScreen ResolutionDeploymentSecurityBrowsersLoad Balance
  • Use HTTP as an Application Protocol – not a Transport Protocol
  • [ExternalReference] [Association("Sales_Customer", "CustomerID", "CustomerID")]

The Full Power of ASP.NET Web API The Full Power of ASP.NET Web API Presentation Transcript

  • Browser RequestIndex.htmlMVC4Traditional Request / Response for ALL rendered content and assets
  • Initial RequestApplication.htmMVC4RequireJS LoaderPage1 Partial.htmIndexViewModel.jsApplication.js (bootstrap)ViewModel (#index)ViewModel (#login)Model (LoginModel)JSON RequestsHTML5 localstorageHandling disconnection
  • Source: www.programmableweb.com – current APIs: 4,535
  • 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
  • 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>
  • 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 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>
  • 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" 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
  • 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: text/html | application/jsonAccept: text/html, application/xhtml+xml, application/xml
  • 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; 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; }}
  • 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>();}
  • 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.
  • “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 };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)};}
  • public class ProductMD{[StringLength(50), Required]public string Name { get; set; }[Range(0, 9999)]public int Weight { get; set; }}
  •  [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]
  • 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);}}}
  • 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);}}}
  • 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());}
  • 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();}
  • http://www.asp.net/web-api/Why I’m giving REST a restBuilding Hypermedia Web APIs with ASP.NET Web API
  • eyalvardi.wordpress.com