Introduction to the ASP.NET Web API
2012-07-23 08:09
417 查看
Introduction to the ASP.NET Web API
摘自 http://stephenwalther.com/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx猛然发现这么一篇介绍asp.net web api的文章竟然被墙了,copy至此。
I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site — then you need to use Ajax. Otherwise, you are just being cruel to your customers.
We use Ajax extensively in several of the ASP.NET applications that my company, Superexpert.com, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser.
One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions.
Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the ASP.NET Web API. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications.
The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API.
Creating an ASP.NET Web API Controller
The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box.Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the Empty API controller template:
A brand new API controller looks like this:
Using jQuery to Retrieve, Insert, Update, and Delete Data
Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this:Getting a Single Record with the ASP.NET Web API
To support retrieving a single movie from the server, we need to add a Get method to our API controller:After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: ]http://localhost:[port]/api/movie/1 (You’ll need to enter the correct randomly generated port).
In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE — is used to identify the action to invoke.
The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1.
The default route for the Web API is defined in the Global.asax file and it looks like this:
Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application).
You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method:
Getting a Set of Records with the ASP.NET Web API
Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies:Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page:
Inserting a Record with the ASP.NET Web API
Now let’s modify our Movie API controller so it supports creating new records:When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response.
Because the name of our method starts with “Post”, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request.
The following HTML page invokes the PostMovie() method.
The HTTP Post operation is performed with the following call to the jQuery $.ajax() method:
Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string.
Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code.
Updating a Record with the ASP.NET Web API
Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request:The following HTML page illustrates how you can invoke the PutMovie() method:
Deleting a Record with the ASP.NET Web API
Here’s the code for deleting a movie:The following page illustrates how you can invoke the DeleteMovie() action:
Performing Validation
How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free.Let’s modify our Movie class so it includes some of the standard validation attributes:
Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database:
The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages:
If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert:
(Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness)
This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation
His validation filter looks like this:
Querying using OData
The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here:http://odata.org
For example, here are some of the query options which you can use with OData:
· $orderby – Enables you to retrieve results in a certain order.
· $top – Enables you to retrieve a certain number of results.
· $skip – Enables you to skip over a certain number of results (use with $top for paging).
· $filter – Enables you to filter the results returned.
The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable.
For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies:
/api/movie?$top=2&$orderby=Title
Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results:
By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time.
The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples:
Return every movie directed by Lucas:
/api/movie?$filter=Director eq ‘Lucas’
Return every movie which has a title which starts with ‘S’:
/api/movie?$filter=startswith(Title,’S')
Return every movie which has an Id greater than 2:
/api/movie?$filter=Id gt 2
The complete documentation for the $filter option is located here:
http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption
Summary
The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API.I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery.
Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option.
I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.
相关文章推荐
- Introduction to ASP.NET Web API
- An Introduction to ASP.NET Web API
- Introduction to ASP.NET Web Programming Using the Razor Syntax (C#)
- [转]Web API Introduction to OData Services using ASP.NET Web API
- The introduction to Web.config of ASP.NET #Reprinted#
- Simple way to implement caching in ASP.NET Web API
- Use the MachineKey API to protect values in ASP.NET
- The service cannot be activated because it does not support ASP.NET compatibility. ASP.NET compatibility is enabled for this application. Turn off ASP.NET compatibility mode in the web.config or add the AspNetCompatibilityRequirements attribute to the ser
- Pluralsight Introduction to the ASP.NET Web API
- Adding the Test API in The ASP.NET Web API Help Page
- How to pass javascript complex object to ASP.NET Web Api and MVC
- ASP.NET AJAX Roadmap--Getting Started (4): Introduction to the UpdatePanel Control
- Building a Web Application->Introduction to ASP.NET Pages
- ASP.Net DebugError解决方案[转]:Unable to start debugging on the web server.Debugging failes because integrated Windows authentication is not enabled.
- ASP.NET AJAX Roadmap--Getting Started (5): Introduction to the UpdateProgress Control
- ASP.NET AJAX Roadmap--Getting Started (6): Introduction to the Timer Control
- How to Migrate from WCF Web API to ASP.NET Web API
- ASP.NET MVC & Web API Brief Introduction
- How do I get ASP.NET Web API to return JSON instead of XML using Chrome
- How to Redirect in ASPNET Web API