Language

See ASP.NET Web API in action with these samples

HttpClient Samples

code sample

Bing Translate Sample | Source Code
Shows how to call the Microsoft Translator service using the HttpClient class. The Microsoft Translator service API requires an OAuth token, which the application obtains by sending a request to the Azure token server for each request to the translator service. The result from the token server is fed into the request sent to the translation service. Before running this sample, you must obtain an application key from Azure Marketplace and fill in the information in the AccessTokenMessageHandler sample class.

code sample

Google Maps Sample | Detailed Description | Source Code
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.

code sample

Twitter Client Sample | Detailed Description | Source Code
Shows how to write a simple Twitter client using HttpClient. The sample uses an HttpMessageHandler to insert OAuth authentication information into the outgoing HttpRequestMessage. The result from Twitter is read using JSON.NET. Before running this sample, you must obtain an application key from Twitter, and fill in the information in the OAuthMessageHandler sample class.

code sample

World Bank Sample | Detailed Description | VS 2010 Source | VS 2012 Source
Shows how to retrieve data from the World Bank data site, using JSON.NET to parse the result.

Web API Samples

code sample

Getting Started with ASP.NET Web API | Source Code
Shows how to create a basic web API that supports HTTP GET requests. Contains the source code for the tutorial Your First ASP.NET Web API.

code sample

Action Results Sample | Source Code
This sample demonstrates custom action results with Web API. An OkTextPlainResult provides a way to return text content via Web API. An OkFileDownloadResult provides a way to return an attachment-style file download to a browser via Web API.

code sample

Basic Authentication Sample | Source Code
This sample demonstrates a custom authentication filter with Web API. It uses the HTTP Basic Access Authentication scheme defined by RFC 2617 combined with the ASP.NET Identity system for storing user names, passwords, roles and claims.

code sample

ASP.NET Web API JavaScript Scenarios – Comments | Source Code
Shows how to use ASP.NET Web API to build web APIs that support browser clients and can be easily called using jQuery.

code sample

ASP.NET Web API Self-Host | Source Code
Shows how to use ASP.NET Web API to self host a simple web API in your own process.

code sample

Contact Manager | Source Code
This sample uses ASP.NET Web API to build a simple contact manager application. The application consists of a contact manager web API that is used by an ASP.NET MVC application and a Windows Phone application to display and manage a list of contacts.

code sample

Attribute Routing Sample | Detailed Description | Source Code
The AttributeRouting library is a NuGet package provided by Tim McCall and others, which lets you specify routes using attributes directly on your API controllers and actions. This sample illustrates some of these features with ASP.NET Web API.

code sample

Azure Blobs File Upload Sample | Source Code
Shows how to use the Azure Blob Storage to store files uploaded to a Web API controller using MIME multipart file upload.

code sample

BSON Formatting Sample | Source Code
This ASP.NET Web API sample illustrates how to use the new BsonMediaTypeFormatter class. This class supports the application/bson media type and BSON format.

code sample

Client Certificate Sample | Detailed Description | Source Code
This sample shows how to create a controller protected using a client certificate with SSL. It shows how to get the certificate on the server side and validate it.

code sample

Content Controller Sample | Detailed Description | VS 2010 Source | VS 2012 Source
Shows how to read and write request and response entities asynchronously using streams. The sample controller has two actions: a PUT action that reads the request entity body asynchronously and stores it in a local file, and a GET action that returns the contents of the local file.

code sample

Controller Specific Configuration Sample | Detailed Description | Source Code
Shows how to set controller-specific configurations. The sample defines an attribute which derives from IControllerConfiguration. When put on a controller, the attribute define specific settings that only apply to that controller.

code sample

Custom Action Selector Sample | Source Code
This sample shows how to use a custom Action Selector in ASP.NET Web API to dynamically chose an action for each request. When a controller is attributed with a class implementing IControllerConfiguration, the attribute class can customize controller-level services to configure the desired behavior. In this sample the BetaTestingBehaviorAttribute implements A/B testing when the 'x-beta-tester' header is present and set to true by randomly sending a portion of users to a 'beta' version of each action.

code sample

Custom Assembly Resolver Sample | Source Code
Shows how to modify ASP.NET Web API to support discovery of controllers from a dynamically loaded library assembly. The sample implements a custom IAssembliesResolver which calls the default implementation and then adds the library assembly to the default results.

code sample

Custom Media-Type Formatter Sample | Detailed Description | Source Code
Shows how to create a custom media type formatter using the BufferedMediaTypeFormatter base class. This base class is intended for formatters which primarily use 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.

code sample

Info Sample | Source Code
This sample illustrates how to use extensiblity points in the ODataFormatter and plugin custom OData serializers/deserializers. The sample extends the ODataFormatter to add support of OData instance annotations.

code sample

Custom Parameter Binding Sample | Detailed Description | Source Code
Shows how to customize the parameter binding process, which is the process that determines how information from a request is bound to action parameters.

code sample

Delta Json Deserialization Sample | Source Code
This sample shows how to configure Json.NET to deserialize the Delta<T> type from Web API 2-2.1 OData. The Delta<T> type is typically used inside the OData protocol to allow partial updates for object using the HTTP PATCH method. This sample will demonstrate how to use the Delta<T> type with the popular Json.NET to support patching and other operations without using the OData protocol.

code sample

Elmah Sample | Source Code
This sample demonstrates custom exception logging and handling with Web API. An ElmahExceptionLogger logs all exceptions for viewing through ELMAH. A GenericTextExceptionHandler sends back static text any time an unhandled exception occurs.

code sample

Entity Framework Code First Sample | Detailed Description | Source Code
Shows 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. 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.

code sample

ETW Tracing Sample | Source Code
Shows how to create an ASP.NET Web API ITraceWriter implementation to write to Event Tracing for Windows (ETW).

code sample

File Upload Sample | Detailed Description | Source Code
Shows how to upload files to an ApiController using MIME Multipart File Upload, and how to set up progress notifications with HttpClient using ProgressNotificationHandler. The controller reads the contents of an HTML file upload asynchronously and writes one or more body parts to a local file. The response contains information about the uploaded file (or files).

code sample

Batch Sample | Detailed Description | Source Code
This sample shows how to use request batching in Web API 2. Batching is a Web API feature that allows a customer to pack several API requests and send them to the Web API service in one HTTP request and receive a single HTTP response with the response to all their requests. This way, the client can optimize calls to the server and improve the latency and scalability of its service.

code sample

Hosted Client Certificate Sample | Detailed Description | Source Code
Shows how to use client certificates to authenticate clients in a web-hosted Web API application.

code sample

Http Message Handler Pipeline Sample | Detailed Description | Source Code
Shows how to wire up HttpMessageHandler instances on both the client (HttpClient) and server (ASP.NET Web API). In the sample, the same handler is used on both the client and server. While it is rare that the exact same handler would run in both places, the object model is the same on client and server side.

code sample

JSON Upload Sample | Source Code
Shows how to upload and download JSON to and from an ApiController. The sample uses a minimal ApiController and accesses it using HttpClient.

code sample

Mashup Sample | Detailed Description | Source Code
Shows how to access multiple remote sites asynchronously from within an ApiController action. Each time the action is hit, the requests are performed asynchronously, so that no threads are blocked.

code sample

Memory Tracing Sample | Detailed Description | Source Code
This sample project creates a Nuget package that will install a custom in-memory trace writer into ASP.NET Web API applications.

code sample

MongoDB Sample | Detailed Description | Source Code
Shows how to use MongoDB as the persistent store for an ApiController, using a repository pattern.

code sample

Namespace Controller Selector Sample | Source Code
Shows how to support multiple API controllers with the same name in different namespaces, by providing a custom implementation of the IHttpControllerSelector interface.

code sample

NHibernate Queryable Sample | Source Code
Sample shows how to apply OData query options to a custom back-end that is not IQueryable.

code sample

OData Actions Sample | Source Code
Shows various ways to implement OData actions in ASP.NET Web API (always-bindable, tansient, non-bindable, etc.).

code sample

OData Batch Sample | Source Code
This sample shows how to use request batching in Web API 2 OData. Batching is a Web API feature that allows a customer to pack several API requests and send them to the Web API service in one HTTP request and receive a single HTTP response with the response to all their requests.

code sample

OData Composite Key Sample | Source Code
Shows how to create an OData service for an entity with a composite key, and how to provide basic CRUD functionality for it.

code sample

OData External Edm Model Sample | Source Code
This sample shows how to use an external IEdmModel with Web API 2 OData. This concrete example exposes the IEdmModel generated by Entity Framework as an OData service.

code sample

OData Paging Sample | Source Code
Shows how to implement server-driven paging using OData.

code sample

OData Queryable Sample | Detailed Description | Source Code
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.

code sample

OData Service Sample | Detailed Description | Source Code
This sample illustrates how to create an OData service consisting of three entities and three Web API controllers. The controllers provide various levels of functionality in terms of the OData functionality they expose.

code sample

OData Versioning Sample | Source Code
Shows how to create multiple versions of an OData service in the same application, and how to support versioning by route, query string and header.

code sample

OWIN Self-Host Sample | Detailed Description | Source Code
Shows how to self-host Web API using Open Web Interface for .NET (OWIN).

code sample

Push Content Sample | Detailed Description | Source Code
Shows how to use the PushStreamContent class to write a never-ending response to a client. The controller writes a little bit of data to the client every second until the client disconnects. The client uses HttpClient. To learn how to use it directly in HTML, see 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.

code sample

Relay Sample | Source Code
Shows how to relay requests and responses from a back-end service through a relay controller, asynchronously and without buffering the contents on the server.

code sample

Response Entity Processor Sample | Source Code
Shows how to copy a response entity (that is, an HTTP response body) to a local file before it is transmitted to the client, and perform additional processing on that file asynchronously. The sample implements an HttpMessageHandler that wraps the response entity with one that both writes itself to the output as normal and to a local file.

code sample

Route Constraints and Model Binders by Implementing Matrix Parameters Sample | Source Code
This sample uses route constraints and the custom model binding as a way to support matrix parameters with Web API. The idea of matrix parameters (or matrix URIs) originates from the design at http://www.w3.org/DesignIssues/MatrixURIs.html. The sample implements the support with flexibility in route-matching and model-binding.

code sample

Routing Constraints Sample | Source Code
This sample shows how to use Attribute Routing and Constraints in ASP.NET Web API to dynamically filter controllers by an 'x-api-version' HTTP header. When a route uses Constraints, each constraint has a chance to prevent the route from matching a given request. In this sample, a custom RouteProviderAttribute (VersionedRoute) adds a constraint to each attribute route.

code sample

Select Expand Dollar Value Sample | Source Code
This sample shows how to use $select, $expand and $value within Web API 2 OData.

code sample

Todo Sample | Source Code
This sample illustrates how to write multiple secure clients (browser, Windows Phone, Windows Store) that consume the same backend Web API.

code sample

Upload XDocument Sample | Detailed Description | Source Code
Shows how to upload an XDocument to an ApiController using PushStreamContent and HttpClient.

code sample

Unit Test Sample | Source Code
This sample demonstrates how to create simple unit tests for your Web API 2 application, and how to mock Entity Framework objects.

code sample

Validation Sample | Source Code
Shows how you can use validation attributes on your models in ASP.NET WebAPI to validate the contents of the HTTP request. 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.

code sample

Web Forms Sample | Detailed Description | Source Code
Shows how to use ASP.NET Web API within a Web Forms project.

code sample

RestBugs Sample | Source Code
RestBugs is a simple bug tracking application that shows how to use ASP.NET Web API and the new HTTP Client library to create a hypermedia-driven system. The sample includes both client and server implementations, using ASP.NET Web API. The server uses a custom Razor formatter to generate resource representations. The sample also provides a node.js server to illustrate the benefits that come from using a hypermedia design to decouple clients and servers.

Web API Version Next Preview Samples

These samples are only supported by the latest nightly runtime builds.

code sample

HTTP Range Request Sample | Detailed Description | Source Code
Range requests is the ability in HTTP to request a part of a document based on one or more ranges. Clients can use range requests to recover from interrupted data transfers caused by canceled requests or dropped connections. A client can also use them to request a subset of a larger representation, such as a single segment of a very large document for special processing. This sample uses the ByteRangeStreamContent class to support byte range requests.