Your official information source from the .NET Web Development and Tools group at Microsoft.
Here is a list of the Web API and HttpClient samples you can find in our samples repository on aspnet.codeplex.com. They illustrate various features of Web API and HttpClient targeting either Visual Studio 2010 using .NET 4 or Visual Studio 2012 using .NET 4.5 with async/await language support.
For details on how get up and running with the samples, please see the blog ASP.NET Web API Samples on Codeplex. You can also check out additional information about ASP.NET Web API as well as find the Open Source runtime on Codeplex.
If there are samples that you miss or you find issues then please register an issue and let us know what you think!
Bing Translate Sample | VS 2012 source
Sample illustrating using the Bing translator API from HttpClient. The API requires an OAuth token which we obtain by sending a request to the Azure token server each time we send a request to the translator service. The result from that request is fed into the request sent to the translation service itself. Before you can run this sample you must obtain an application key from Azure Marketplace and fill in the information in the AccessTokenMessageHandler sample class.
Google Maps Sample | detailed description | VS 2012 source
This sample uses HttpClient to download a map of Redmond, WA from Google Maps API, saves it as a local file, and opens the default image viewer.
Twitter Client Sample | detailed description | VS 2012 source
This sample illustrates how to write a simple twitter client using HttpClient. The sample uses an HttpMessageHandler to insert the appropriate OAuth authentication information into the outgoing HttpRequestMessage. The result from twitter is read using JSON.NET as a JToken. Before you can run this sample you must obtain an application key from twitter, and fill in the information in the OAuthMessageHandler sample class.
World Bank Sample | detailed description | VS 2010 source | VS 2012 source
This sample shows how to retrieve data from the World Bank data site using JSON.NET to parse the result as JToken.
Attribute Routing Sample | detailed description | VS 2010 source
AttributeRouting is a great NuGet package provided by Tim McCall and friends which lets you specify routes, constraints, default values, and more using attributes directly on your API controllers and actions. This sample illustrates some of these features with ASP.NET Web API.
File Upload to Azure Blob Store Sample | detailed description | VS 2012 source
This sample is similar to the File Upload Sample but instead of saving the uploaded files on local disk, it asynchronously uploads them to Azure Blob Store using Windows Azure SDK for .NET. It also provides a mechanism for listing the blobs currently present in an Azure Blob Storage Container. You can try out the sample running against Azure Storage Emulator that comes with the Azure SDK and if you have an Azure Storage Account you can run against the real storage service as well.
Client Certificate Sample | detailed description | VS 2010 source for selfhost | VS 2010 source for ASP.NET
This sample illustrates how to create a controller protected using a client certificate with SSL. It describes how to get the certificate on the server side and validate it.
Content Controller Sample | detailed description | VS 2010 source | VS 2012 source
This ASP.NET Web API sample illustrates how to read and write request and response entities asynchronously using streams. The sample controller has two actions: a PUT action which reads the request entity body asynchronously and stores it in a local file and a GET action which returns the content of the local file.
Controller Specific Configuration Sample | detailed description | VS 2012 source
This ASP.NET Web API sample illustrates how to set up per-controller specific configuration. It defines an attribute which derives from IControllerConfiguration which, when put on a controller, can define specific settings that only apply to that controller type.
Custom Assembly Resolver Sample | VS 2012 source
This sample illustrates how to modify ASP.NET Web API to support discovery of controllers loaded dynamically from a dynamically loaded controller library assembly. The sample implements a custom IAssembliesResolver which takes the default implementation providing the default list of assemblies and then adds the ControllerLibrary assembly as well.
Custom Media Type Formatter Sample | detailed description | VS 2010 source
This sample illustrates how to create a custom media type formatter using the BufferedMediaTypeFormatter base class for formatters which primarily are using synchronous read and write operations. In addition to showing the media type formatter, the sample shows how to hook it up by registering it as part of the HttpConfiguration for your application. Note that it is also possible to use the MediaTypeFormatter base class directly for formatters which primarily use asynchronous read and write operations.
Custom Parameter Binding Sample | detailed description | VS 2010 source
This ASP.NET Web API sample illustrates how to customize the parameter binding process which is the process that determines how information from a request is bound to action parameters. In this sample, the Home controller has four actions:
Entity Framework Code First Sample | detailed description | VS 2012 source
This sample demonstrates how to use ASP.NET Web API together with Entity Framework Code First to build an application that helps users find interesting tourist attractions. The application consists of a simple Web page that uses AJAX to talk to a Web API allowing users to locate the tourist attraction closest to a given location. By exposing the data as a Web API applications on a variety of platforms can access the data as well. Just like ASP.NET Web API, in addition to shipping as part of Visual Studio 2012, Entity Framework is available on Codeplex allowing you to dive right into the source and participate.
Tracing using Event Tracing for Windows (ETW) Sample | VS 2012 source
This sample illustrates how to create an ASP.NET Web API ITraceWriter implementation to write to Event Tracing for Windows (ETW).
File Upload Sample | detailed description | VS 2012 source
This sample illustrates how to upload files to an ApiController using HttpClient using MIME Multipart File Upload as defined by HTML. It also shows how to set up progress notifications with HttpClient using ProgressNotificationHandler. The FileUploadController reads the contents of an HTML file upload asynchronously and writes one or more body parts to a local file. It then responds with a result containing information about the uploaded file (or files).
Batching Sample | detailed description | VS 2012 source
This sample shows how to implement HTTP batching within ASP.NET. The batching consists of putting multiple HTTP requests within a single MIME multipart entity body which is then sent to the server as an HTTP POST. The requests are then processed individually and the responses are put into another MIME multipart entity body which is returned to the client.
Http Message Handler Pipeline Sample | detailed description | VS 2010 source
This sample illustrates how to wire up HttpMessageHandlers on both client and server side as part of either HttpClient or ASP.NET Web API. In the sample, the same handler is used on both client and server side. While it is rare that the exact same handler can run in both places, the object model is the same on client and server side.
JSON Upload Sample | VS 2012 source
This sample illustrates how to upload and download JSON to and from an ApiController. The sample uses a minimal ApiController and accesses it using HttpClient.
Mashup Sample | detailed description | VS 2012 source
This sample shows how to asynchronously access multiple remote sites from within an ApiController action. Each time the action is hit, the requests are performed asynchronously so that no threads are blocked.
Memory Tracing Sample | detailed description | VS 2010 source
MongoDB Sample | detailed description | VS 2012 source
This sample illustrates how to use MongoDB as the persistent store for an ApiController using a repository pattern.
Custom Http Controller Selector Sample | detailed description | VS 2012 source
This ASP.NET Web API sample shows how to support multiple API controllers with the same name in different namespaces. For example, you could define two controllers named "ValuesController" in two different CLR namespaces:
The sample makes it possible to invoke the two different versions of the controller with these URIs:
Translating OData Queries to NHibernate’s HQL Query Language | detailed description | VS 2012 source
NHibernate is an ORM layer on .NET platform. It is a .NET port of the Java ORM Hibernate. NHibernate uses a query language HQL (Hibernate Query Language) that is similar in appearance to SQL. Compared with SQL, however, HQL is fully object-oriented and understands notions like inheritance, polymorphism and association.
This sample uses NHibernateFluent to define the object-database mappings and is using SQLite as the backend store. It demonstrates how to translate $skip, $top, $orderby, and $filter to HQL.
OData Composite Key Sample | detailed description | VS 2010 source
This sample illustrates how to create an OData service consisting of entity with composite key and how to provide basic CRUD functionalities on it. The data model contains one entity (Person) with two keys (FirstName and LastName). The OData URI for this model will look like this: http://localhost:33051/People(FirstName='Kate',LastName='Jones'). This sample shows how to write the OData controller so that you can have full CRUD support with parameter binding etc.
OData Server Paging Sample | VS 2010 source
The server controls the page size by using the ResultLimit property on the [Queryable] attribute. Modifying this value allows the server to change the page size for the client without requiring any changes to the client itself.
OData Queryable Sample | detailed description | VS 2010 source
This sample shows how to introduce OData queries in ASP.NET Web API using either the [Queryable] attribute or by using the ODataQueryOptions action parameter which allows the action to manually inspect the query before it is being executed.
The CustomerController shows using [Queryable] attribute and the OrderController shows how to use the ODataQueryOptions parameter. The ResponseController is similar to the CustomerController but instead of the GET action returning IEnumerable<Customer> it returns an HttpResponseMessage. This allows us to add extra header fields, manipulate the status code, etc. while still using query functionality. The sample illustrates queries using $orderby, $skip, $top, any(), all(), and $filter.
OData Service Sample | detailed description | VS 2010 source
This sample illustrates how to create an OData service consisting of three entities and three ApiControllers. The controllers provide various levels of functionality in terms of the OData functionality they expose:
The SupplierController exposes a subset of functionality including Query, Get by Key and Create, by handling these requests:
The ProductsController exposes GET, PUT, POST, DELETE, and PATCH by implementing an action for each of these operations directly.
The ProductFamilesController leverages the EntitySetController base class which exposes a useful pattern for implementing a rich OData service.
In addition the OData service exposes a $metadata document which allows the data to the consumed by WCF Data Service clients and other clients that accept the $metadata format.
OData Versioning Sample | VS 2012 source
This sample illustrates how to create multiple versions of OData service in same application and how to support versioning by route, query string and header.
Push Content Sample | detailed description | VS 2010 source
This sample illustrates using PushStreamContent to write a never-ending response to a client. The PushContentController writes a little bit of data to the client every second until the client disconnects. The client is a regular HttpClient sample but you can also see the blog Native HTML5 push notifications with ASP.NET Web API and Knockout.js and Real-Time Chart using HTML5 Push Notification (SSE) and ASP.NET Web API for how to leverage this directly in HTML.
Relay Sample | VS 2012 source
This sample shows how to relay an HTTP request and response from a backend service through a relay controller asynchronously and without buffering the contents on the server. A request and response flows as follows: Client <—> Relay <—> Service. The data flow is such that all data is exchanged asynchronously (both upload and download) and without buffering the contents in the Relay. This allows the sample to pipe though many GBytes without running out of resources.
Response Body Processor Sample | VS 2012 source
This sample illustrates how to copy a response entity (i.e. an HTTP response body) to a local file before it is transmitted to the client and perform additional processing on that file asynchronously. It does so by hooking in a HttpMessageHandler that wraps the response entity with one that both writes itself to the output as normal and to a local file.
Upload XDocument Sample | detailed description | VS 2012 source
This sample illustrates uploading an XDocument to an ApiController using PushStreamContent and HttpClient.
Validation Sample | VS 2010 source
This sample illustrates how you can use validation attributes on your models in ASP.NET WebAPI to validate the contents of the HTTP request. It demonstrates how to mark properties as required, how to use both framework-defined and custom validation attributes to annotate your model, and how to return error responses for invalid model states.
Web Form Sample | detailed description | VS 2010 source
This sample shows an ApiController added to a WebForm project using the menu "Add New Item" and then select "Web API Controller Class". In addition to the controller we also add a default route to global.asax.cs file.
These are samples that are only supported by the latest nightly runtime builds.
Http Byte Range Sample | detailed description | VS 2010 source
Range requests is the ability in HTTP to request a part of a document based on one or more ranges. This can be used in scenarios where the client wants to recover from interrupted data transfers as a result of canceled requests or dropped connections. It can also be used in scenarios where a client requests only a subset of a larger representation, such as a single segment of a very large document for special processing. This samples demonstrates using the ByteRangeStreamContent class to support byte range requests.
Also check out versioning in ASP.NET Web API: damsteen.nl/.../implementing-versioning-in-asp.net-web-api
It shows how flexible and pluggable the framework really is. :)
This was a great post Henrik. Thanks for the web API samples you have shared. - <a href="www.hireawiz.com/.../phoenix-web-design">Phoenix web development</a>