Beruflich Dokumente
Kultur Dokumente
Home
Get Started
Downloads
Web Pages
Web Forms
MVC
Solutions
Community
Forums
Overview
Videos
Samples
Forum
What's coming in the next version of
Home / Web API / Overview / Chapter 1. Getting Started with ASP.NET Web API / Your First Web API
TABLE OF CONTENTS Getting Started with ASP.NET Web API ASP.NET Web API, Part 1: Your First Web API Your First Web API (C#) Building HTTP services with ASP.NET Web API in MVC 4 Beta Creating Web APIs Creating a Web API that Supports CRUD Operations Sample: Contact Manager Web API Routing and Actions Routing in ASP.NET Web API Paging and Querying Exception Handling in ASP.NET Web API ASP.NET Web API, Part 2: Getting Data ASP.NET Web API, Part 3: Delete and Update ASP.NET Web API, Part 4: Paging and Querying ASP.NET Web API, Part 5: Custom Validation ASP.NET Web API, Part 6: Authorization Working with HTTP HTTP Message Handlers Sample: Introduction to HttpClient Forms and Multi-part MIME Formats and Model Binding
In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.
Media Formatters Hosting ASP.NET Web API Self-Host a Web API (C#) Sample: ASP.NET Web API Self-Host Using Web API with ASP.NET Web Forms Testing and Debugging Tracing in ASP.NET Web API Extensibility Using the Web API Dependency
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
1/10
19/05/2012
Adding a Model
A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message. To see all of this in action, let's start by creating a simple model. If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context meny, select Add then select Class.
Name the class "Product". Next, add the following properties to the Product class. nmsaeHloeAIMdl aepc elWbP.oes
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
2/10
19/05/2012
{
pbi casPout ulc ls rdc { pbi itI {gt st } ulc n d e; e; pbi srn Nm {gt st } ulc tig ae e; e; pbi dcmlPie{gt st } ulc eia rc e; e; } }
Adding a Controller
A controller is an object that handles HTTP requests from the client. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in Solution Explorer. HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site, and is not directly related to our Web API service. ValuesController is an example WebAPI controller. Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data. Let's rename ValuesController. In Solution Explorer, right-click ValuesController.cs and select Rename.
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
3/10
19/05/2012
When you type Enter, Visual Studio will prompt you whether to rename all references to the code element "ValuesController":
Click Yes. This will cause Visual Studio to rename the class definition along with the file name: nmsaeHloeAICnrles aepc elWbP.otolr { pbi casPoutCnrle :Aiotolr ulc ls rdcsotolr pCnrle { / Mtosntson. / ehd o hw.. } }
Delete the existing methods from the ProductsController class. Then add the following two methods: pbi InmrbePout GtlPout( ulc Eueal<rdc> eAlrdcs) { rtr nwLs<rdc> eun e itPout { nwPout){I =1 Nm ="im 1,Pie=19M} e rdc( d , ae Gzo " rc .9 , nwPout){I =2 Nm ="im 2,Pie=29M} e rdc( d , ae Gzo " rc .9 , nwPout){I =3 Nm ="im 3,Pie=39M} e rdc( d , ae Gzo " rc .9 } ; } pbi PoutGtrdcBI(n i) ulc rdc ePoutydit d { i (d<1| i >3 f i | d )
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
4/10
19/05/2012
{
trwnwHtRsosEcpinSse.e.tpttsoeNton) ho e tpepnexeto(ytmNtHtSauCd.oFud; } rtr nwPout){I =i,Nm ="im "+i.otig) Pie=i +09M} eun e rdc( d d ae Gzo dTSrn(, rc d .9 ; }
The GetAllProducts method returns a list of products, as an IEnumerable<Product> type. The GetProductById method returns a product specified by ID value. For this tutorial, we want to keep the code as simple as possible, so both methods return hard-coded values. In the case of GetProductById, we set the product name to "Gizmo id". For example, if the user requests ID = 2, the method returns "Gizmo 2". Notice that GetProductId throws an exception of type HttpResponseException if id is not valid. This exception will be translated by the framework into a 404 (Not Found) error. That's it! You have a working HTTP service. Now let's write a client to access the service.
Index.cshtml renders HTML using the Razor view engine. However, we will not use any Razor features in this tutorial, because I want to show how a client can access the service using plain HTML and Javascript. Therefore, go ahead and delete everything in this file, and replace it with the following: <DCYEhm> !OTP tl <tlln=e" hm ag"n> <ed ha> <il>S.E WbAI/il> tteAPNT e P<tte <citsc"../cit/qey162mnj" srp r=./.Srpsjur-...i.s tp=tx/aacit>/cit ye"etjvsrp"<srp> <ha> /ed <oy bd> <i> dv <1AlPout<h> h>l rdcs/1 <li=pout'/ u d'rdcs > <dv /i> <i> dv <ae fr"rdd>D<lbl lbl o=poI"I:/ae> <nu tp=tx"i=poI"sz=5/ ipt ye"et d"rdd ie""> <nu tp=bto"vle"erh ocik"id)"/ ipt ye"utn au=Sac" nlc=fn(; > < i=pout / p d"rdc" > <dv /i> <bd> /oy <hm> /tl
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
5/10
19/05/2012
<cittp=tx/aacit> srp ye"etjvsrp" $dcmn)rayfnto ( { (ouet.ed(ucin ) / Sn a AA rqet / ed n JX eus $gtSN"p/rdcs" .eJO(aipout/, fnto (aa { ucin dt) / O sces 'aa cnan als o pout. / n ucs, dt' otis it f rdcs $ec(aa fnto (e,vl { .ahdt, ucin ky a) / Fra tetx t dsly / omt h et o ipa. vrsr=vlNm +' $ +vlPie a t a.ae : ' a.rc; / Adals ie frtepout / d it tm o h rdc. $'l/' {hm:sr} (<i>, tl t ) .pedo$'pout') apnT((#rdcs); }; ) }; ) }; ) <srp> /cit
The getJSON function sends the AJAX request. The response will be an array of JSON objects. The second parameter to getJSON is a callback function that is invoked when the request successfully completes.
Getting a Product By ID
To get a product by ID, send an HTTP GET request to "/api/products/id", where id is the product ID. Add the following code to the script block: fnto fn( { ucin id) vri =$'poI'.a(; a d (#rdd)vl) $gtSN"p/rdcs"+i, .eJO(aipout/ d fnto (aa { ucin dt) vrsr=dt.ae+' $ +dt.rc; a t aaNm : ' aaPie $'pout)hm(t) (#rdc'.tlsr; } ) .al fi( fnto (qH,txSau,er { ucin jXR ettts r) $'pout)hm(Err '+er; (#rdc'.tl'ro: r) }; ) }
Again, we call the jQuery getJSON function to send the AJAX request, but this time we use the ID to construct the request URI. The response from this request is a JSON representation of a single Product object. The following code shows the complete Index.cshtml file. <DCYEhm> !OTP tl <tlln=e" hm ag"n> <ed ha> <il>S.E WbAI/il> tteAPNT e P<tte <citsc"../cit/qey162mnj"tp=tx/aacit>/cit srp r=./.Srpsjur-...i.s ye"etjvsrp"<srp> <cittp=tx/aacit> srp ye"etjvsrp" $dcmn)rayfnto ( { (ouet.ed(ucin ) / Sn a AA rqet / ed n JX eus $gtSN"p/rdcs" .eJO(aipout/, fnto (aa { ucin dt) / O sces 'aa cnan als o pout. / n ucs, dt' otis it f rdcs $ec(aa fnto (e,vl { .ahdt, ucin ky a) / Fra tetx t dsly / omt h et o ipa. vrsr=vlNm +' $ +vlPie a t a.ae : ' a.rc; / Adals ie frtepout / d it tm o h rdc. $'l/' {hm:sr}.pedo$'pout') (<i>, tl t )apnT((#rdcs); }; ) }; ) }; ) fnto fn( { ucin id) vri =$'poI'.a(; a d (#rdd)vl) $gtSN"p/rdcs"+i, .eJO(aipout/ d fnto (aa { ucin dt) vrsr=dt.ae+' $ +dt.rc; a t aaNm : ' aaPie $'pout)hm(t) (#rdc'.tlsr; } ) .al fi(
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
6/10
19/05/2012
} <srp> /cit <ha> /ed <oy bd> <i> dv <1AlPout<h> h>l rdcs/1 <li=pout'/ u d'rdcs > <dv /i> <i> dv <ae fr"rdd>D<lbl lbl o=poI"I:/ae> <nu tp=tx"i=poI"sz=5/ ipt ye"et d"rdd ie""> <nu tp=bto"vle"erh ocik"id)"/ ipt ye"utn au=Sac" nlc=fn(; > < i=pout / p d"rdc" > <dv /i> <bd> /oy <hm> /tl
It's not flashy, but it shows that our HTTP service is working. You can get a product by ID by entering the ID in the text box:
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
7/10
19/05/2012
Understanding Routing
For each HTTP message, the ASP.NET Web API framework decides which controller receives the request by consulting a table. We'll discuss routing in more detail in another tutorial, but here is a quick overview. When you create a new Web API project, the project contains a default route that looks like this: /api/{controller}/{id} The {controller} and {id} portions are placeholders. When the framework sees a URI that matches this pattern, it looks for a controller method to invoke, as follows: {controller} is matched to the controller name. The HTTP request method is matched to the method name. (This rule applies only to GET, POST, PUT, and DELETE requests.) {id}, if present, is matched to a method parameter named id. Here are some example requests, and the action that results from each, given our current implementation. HTTP Method GET GET POST GET URI /api/products /api/products/5 /api/products/ /api/users/ Action GetAllProducts() GetProduct(5) HTTP Status 405 HTTP Status 404
In the first example, "products" matches the controller named ProductsController. The request is a GET request, so the framework looks for a method on ProductsController whose name starts with "Get...". Furthermore, the URI does not contain the optional {id} segment, so the framework looks for a method with no parameters. The ProductsController::GetAllProducts method meets all of these requirements. The second example is the same, except that the URI contains the {id} portion. Therefore, the frameworks calls GetProduct, which takes a parameter named id. Also, notice that value "5" from the URI is passed in as the value of the id parameter. The framework automatically converts the "5" to an int type, based on the method signature. In the third example, the client sends an HTTP POST request. The framework looks for a method whose name starts with "Post..." However, no such method exists in ProductsController, so the framework returns an HTTP response with status 405, Method Not Allowed. In the fourth example, the client sends a GET request to /api/users. The framework looks for a controller named UsersController. We did not define a controller with that name, so the frameworks returns status 404, Not Found.
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
8/10
19/05/2012
Locate the entry for the relative URI api/products/. Select this entry and click Go to detailed view. In the detail view, there are tabs to view the request and response headers and bodies. For example, if you click the Request headers tab, you can see that the client requested "application/json" in the Accept header.
If you click the Response body tab, you can see how the product list was serialized to JSON: ["d:,Nm""im 1,Pie:.9, {I"1"ae:Gzo ""rc"19} {I"2"ae:Gzo2,Pie:.9, "d:,Nm""im ""rc"29} {I"3"ae:Gzo3,Pie:.9] "d:,Nm""im ""rc"39}
Comments (26)
Show Comments
Powered by
and Umbraco
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
9/10
19/05/2012
www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
10/10