adding webapi to aspnet site
DESCRIPTION
ASP.NET MVC 4 WebAPI presentationTRANSCRIPT
![Page 1: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/1.jpg)
Microsoft /web
®
WebCamps OnlineTwitter: Follow @webcampsHashtag #devampsSPEAKER NAME/HANDLE HERE
Website: http://www.devcamps.ms/web
What are web camps?Web Developer Camps are free, fun, no-fluff events for developers, by developers. You learn from experts in a low-key, interactive way and then get hands-on time to apply what you’ve learned.
![Page 2: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/2.jpg)
Microsoft /web
®
Building a Service Layer
with ASP.NET Web APINameTitleMicrosoft Corporation
![Page 3: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/3.jpg)
Agenda
Why all the hype for Web APIs?
Building Web APIs for browser/JSON clients
Building Web APIs for native/non-browser clients
![Page 4: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/4.jpg)
Microsoft /web
®
Today
Today if you want to reach your user, you have to reach their device
In this talk you’ll learn how
![Page 5: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/5.jpg)
Microsoft /web
®
Comparison of WCF & ASP.NET Web API
WCF
• Back-end Services• SOAP, WS-*• Transports: HTTP, TCP,
UDP, Queues, WebSockets, custom
• Message patterns: request-reply, one-way, duplex
• Use WCF Web HTTP to add HTTP endpoints to existing WCF services
• Use WCF Data Services for full OData support
ASP.NET Web API
• Front-end Services• Media Types: JSON, XML,
form-URL-encoded, custom
• HTTP only• Request-reply only• REST, resource-centric• Use SignalR for
asynchronous signaling (polling, long-polling, WebSockets)
![Page 6: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/6.jpg)
Microsoft /web
®
Web API is a part of ASP.NET
Caching
Modules Handlers
Intrinsics
Membership
Etc.
ASP.NET Core
MVCWeb Pages
Web Forms
Razor View Engine
MVC 4
HTML
Web API
Code
JSON
XML
![Page 7: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/7.jpg)
Microsoft /web
®
Where Can You Get Web API?
![Page 8: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/8.jpg)
Microsoft /web
®
Homepage: asp.net/web-api
![Page 9: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/9.jpg)
Microsoft /web
®
Find Us on Nuget
Nuget PackagesWebApi
WebApi.OData
JsonValue
HttpClient
WebApi.Enhancements
![Page 10: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/10.jpg)
Microsoft /web
®
Building a Read Only Web API
Why?Allow browser or other clients to easily retrieve information from your system
![Page 11: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/11.jpg)
Microsoft /web
®
Sample Read-only Model and Controller public class Person
{ public int Id { get; set; } public string Name { get; set; }}
Step 1:Create a Model
public class PersonController : ApiController{ List<Person> _people; public PersonController() { _people = new List<Person>(); _people.AddRange(new Person[] { new Person { Id = 1, Name = "Chuck Norris" }, new Person { Id = 2, Name = "David Carradine" }, new Person { Id = 3, Name = "Bruce Lee" } }); }}
Step 2:Make an API Controller
![Page 12: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/12.jpg)
Microsoft /web
®
Read-only Controller Actions to return data // GET /api/person
public IEnumerable<Person> Get(){ return _people;}
Step 3:Return everything
// GET /api/person/5public Person Get(int id){ return _people.First(x => x.Id == id);}
Step 4:Return one item
![Page 13: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/13.jpg)
Microsoft /web
®
Routing a Web API Using Global.asax.cs
public static void RegisterRoutes(RouteCollection routes){ routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );}
Routing:Familiar syntax, conventional approach
![Page 14: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/14.jpg)
Microsoft /web
®
Manipulating HTTP Responses
// GET /api/person/5public HttpResponseMessage<Person> Get(int id){ try { var person = _people.First(x => x.Id == id);
return new HttpResponseMessage<Person>( person, HttpStatusCode.OK ); } catch { return new HttpResponseMessage<Person>(HttpStatusCode.NotFound); }}
ExampleFind a person and return it,but what happens if we don’t find a match?
![Page 15: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/15.jpg)
Microsoft /web
®
Manipulating HTTP Responses
A successful API call returns an HTTP OK and the JSON data
![Page 16: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/16.jpg)
Microsoft /web
®
Manipulating HTTP Responses
An unsuccessful API call returns an HTTP 404 (and no JSON)
![Page 17: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/17.jpg)
Building a read only Web API
demo
![Page 18: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/18.jpg)
Microsoft /web
®
Making an API Updatable
Why?Allow clients to modify the state of the server
![Page 19: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/19.jpg)
Microsoft /web
®
Posting Data to a Web APIpublic HttpResponseMessage Post(Person person){ person.Id = _people.Count + 1;
if (_people.Any(x => x.Id == person.Id)) return new HttpResponseMessage(HttpStatusCode.BadRequest);
try { _people.Add(person); } catch { return new HttpResponseMessage(HttpStatusCode.BadRequest); }
return new HttpResponseMessage(HttpStatusCode.OK);}
Use HTTP Post:Pass a Model
![Page 20: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/20.jpg)
Microsoft /web
®
Posting Data to a Web API
![Page 21: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/21.jpg)
Making an API updatable
demo
![Page 22: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/22.jpg)
Microsoft /web
®
Supporting HTML File Upload
Why?Allow clients to send files from a browser
![Page 23: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/23.jpg)
Microsoft /web
®
Support HTML File Upload
IsMimeMultipartContent – checks if multipart
MultipartFormDataStreamProvider – parses the streams
BodyPartFileNames – returns the list of files sent in the stream
![Page 24: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/24.jpg)
Microsoft /web
®
Uploading Filespublic async Task<IList<string>> Post(){ List<string> result = new List<string>();
if (Request.Content.IsMimeMultipartContent()) { MultipartFormDataStreamProvider stream = new MultipartFormDataStreamProvider("c:/uploads/");
IEnumerable<HttpContent> bodyparts = await Request.Content.ReadAsMultipartAsync(stream);
IDictionary<string, string> bodyPartFiles = stream.BodyPartFileNames;
bodyPartFiles .Select(i => { return i.Key; }) .ToList() .ForEach(x => result.Add(x)); } return result;}
Use HTTP Post:Pass a Model
![Page 25: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/25.jpg)
Microsoft /web
®
So what happens during upload?Request – Note incoming filename
Response – Note saved filename
![Page 26: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/26.jpg)
HTML file upload
Using HttpContent to work with the body of the request
demo
![Page 27: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/27.jpg)
Microsoft /web
®
Web API is a part of ASP.NET
Caching
Modules Handlers
Intrinsics
Membership
Etc.
ASP.NET Core
MVCWeb Pages
Web Forms
Razor View Engine
MVC 4
HTML
Self Host
Web API
Code
JSON
XML
![Page 28: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/28.jpg)
Microsoft /web
®
Self Hosting Your Web API
Why? More granular controlNo need for a web serverIsolated cases requiring minimal resources viastandard protocol sets
Why Not?
![Page 29: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/29.jpg)
Microsoft /web
®
Configuring Your Web API for Self HostHttpConfiguration provides a code based configuration mechanismNew it up directly or derive from it Pass HttpConfiguration instance to HttpServiceHostFactory/HttpServiceHost
![Page 30: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/30.jpg)
Microsoft /web
®
Self Hosting a Web API Controller is Easy class Program
{ static void Main(string[] args) { // configure the server var baseAddress = "http://localhost:8080/"; var config = new HttpSelfHostConfiguration(baseAddress);
config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );
// Create and open the server var server = new HttpSelfHostServer(config); server.OpenAsync().Wait(); Console.WriteLine("The server is running..."); Console.ReadLine(); }}
Console Host:First set up the configuration and the routes, just like in Global.asax.cs.
Then, host the controllerusing HttpSelfHostServerand open the server up tolisten for requests.
![Page 31: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/31.jpg)
Microsoft /web
®
Self Hosting a Web API Controller is Easy public class EnvironmentStatus
{ public string MachineName { get; set; } public DateTime TimeOnServer { get; set; }}
public class EnvironmentController : ApiController{ public EnvironmentStatus Get() { Console.WriteLine(“User agent " + Request.Headers.UserAgent);
return new EnvironmentStatus { MachineName = Environment.MachineName, TimeOnServer = DateTime.Now }; }}
Controller:This simple controllerprovides information about the server hostingthe controller.
![Page 32: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/32.jpg)
Self Hosting YourWeb API
demo
![Page 33: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/33.jpg)
Microsoft /web
®
Configuring Media Type Formatters Why?Tweak our Xml/Json formattersOData clientsOther native/non-browser clients Custom media types
![Page 34: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/34.jpg)
Configuring media type formatters
ODATA, JSON.NET, HAL
demo
![Page 35: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/35.jpg)
Microsoft /web
®
What We Learned
Why Web APIs are important
How to author Web APIs for multiple clients
How configure a Web API
Enabling HTML file upload
Enabling OData and custom formats
Using the Web API test client
![Page 36: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/36.jpg)
Microsoft /web
®
http://www.asp.net/web-api
http://channel9.msdn.com/Shows/Web+Camps+TV/Dan-Roth-on-the-new-ASPNET-Web-API
http://blogs.msdn.com/b/henrikn/archive/2012/02/19/using-web-api-with-mongodb.aspx
For More Information
![Page 37: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/37.jpg)
Microsoft /web
®
ResourcesFeedback and questions http://forums.dev.windows.com
Session feedbackhttp://bldw.in/SessionFeedback
![Page 38: Adding WebApi To ASPNET Site](https://reader031.vdocument.in/reader031/viewer/2022013110/54651a58b4af9f443f8b4a80/html5/thumbnails/38.jpg)
© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to
be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.