Getting Started: building simple Web APIs

Source: Internet
Author: User
Tags sorted by name

The WCF web API supports multiple host environments: Self-host (Windows service or console) and iis host (Asp.net webform/MVC ). This getting started article mainly demonstrates the website host in ASP. NET mvc3:

  • How to Use nuget to add web API reference to a project
  • How to create a web API accessed through HTTP GET
  • How to host a web API through Asp.net routes
  • How to access Web APIs through a browser or fiddler
  • How to enable odata URI query on APIs
  • How to Use the WCF Web Test client to test the WCF web API

1. Create a basic solution: Use vs2010 to create an empty ASP. net mvc 3 Web Application

Set the site port number to 9000

2. Add web API reference to the solution

Add Assembly reference for web API through nuget, right-click Project properties, and select "manage nuget packages"

Query "webapi. All" of online on the nuget management Extender

 

Select "Install" to download all required software packages. Now you can start to develop Web APIs.

3. Create a contacts API class

Right-click the project contactmanager and choose Add a folder named "APIs". Then, right-click the APIS folder and choose add class. The class name is contactsapi:

using System.ServiceModel;
namespace ContactManager.APIs
{
[ServiceContract]
public class ContactsApi
{
}
}
Adding servicecontractattribute to contractsapi indicates that this is a WCF Service and will be exposed through HTTP. 4. To register contractsapiapi through Asp.net routing, you must use the Asp.net MVC host and register it using the mapserviceroute Extension Method of Asp.net route. Switch to the Global. asax. CS file and add the following reference
using ContactManager.APIs;
using System.ServiceModel.Activation;

Add the following code to the registerroutes method:
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
The yellow section below is very important. The default routing of MVC is mapped to Controller + action.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
Routes. maproute (
"Default", // route name
"{Controller}/{action}/{ID}", // URL with Parameters
New {controller = "home", Action = "Index", id = urlparameter. optional} // parameter defaults
);
}

Mapserviceroute requires a generic parameter to specify the Service (API) and a path to be appended to the IIS base URL. Here, we specify "contacts", that is, the host is "http: // localhost: 9000/API/contacts ".

5. expose contacts through an http get method: first, create a poco (plain old C #) contract class to represent the contacts we transmit on the API. Essentially, it is a DTO (data transmission object ), we use HTTP as a resource and create an http get method to expose the resource.

Right-click the contactmanager project and select "Resources" to add a new class "Contact" under the Resources file.

namespace ContactManager.Resources
{
public class Contact
{
public int ContactId { get; set; }
public string Name { get; set; }
}
}

Return to the contactapi class and add the following reference:

using System.ServiceModel.Web;
using ContactManager.Resources;

Add a get method to return all contracts

[WebGet(UriTemplate = "")]
public IQueryable<Contact> Get()
{
var contacts = new List<Contact>()
{
new Contact {ContactId = 1, Name = "Phil Haack"},
new Contact {ContactId = 2, Name = "HongMei Ge"},
new Contact {ContactId = 3, Name = "Glenn Block"},
new Contact {ContactId = 4, Name = "Howard Dierking"},
new Contact {ContactId = 5, Name = "Jeff Handley"},
new Contact {ContactId = 6, Name = "Yavor Georgiev"}
};
return contacts.AsQueryable();
}

Webget attribute is added to the get method to indicate that this is an http get. Note that the uritemplate here is set to "". By default, the URI of the operation is the method name get. In this case, we set the URI in the route.

6. query the contracts in the browser and press F5 to run the project. Then, enter http: // localhost: 9000/API/contacts in the address bar of the browser.

7. the query returns the contracts in JSON format. HTTP provides some "content negotiation" mechanisms-when there are multiple forms of representation available, select the best form of processing for a specific response.

Server-driven negotiation)

If the best form of response is implemented through algorithms on the server, the server-driven negotiation is called this method. The choice is based on the form of response (the response varies according to different dimensions; for example, language, content encoding, and so on) and the specific header domain in the request message or other information about the request (such as the address of the network client ).

Server-driven negotiation has advantages. It is difficult to describe the user agent by selecting an algorithm from a feasible representation, or when the server expects to send the "best guess" to the client and only responds with one response (to avoid the loop of subsequent requests (a request will return a response) delay if this "Best guess" is suitable for users. To improve server speculation, the user agent should contain the request header domain (Accept, accept-language, accept-encoding, and so on), which can describe its preference for response.

Media types can be easily added to responses returned by Web APIs ).

Open fiddler and enter the address "http: // localhost: 9000/API/contacts" in the "request builder" column ", move to "request headers" and add "accept: Application/JSON" under "User-Agent"

 

Press the exectue button, double-click the panel on the left to view the HTTP response, and switch to the "Raw" tab. You can see the following JSON data:

8. Enable odata query support

The web API supports the odata protocol and accepts the URI format query of odata. When the odata query reaches the web API, the necessary filtering and sorting will be performed on the server before the client is returned. The iqueryable interface is used for query. The server does not query all the data and sends the data to the server for filtering and sorting.

return contacts.AsQueryable();

Run the program and enter http: // localhost: 9000/API/contacts? $ Top = 4 & $ orderby = Name. the browser returns the top 4 contract sorted by name.

You can also use fidder to query data. For more information, see step 1.

9. the WCF web API also provides a WCF Web Test client for testing the WCF web API. by enabling the configuration, create an httpconfiguration instance in the registerroutes method and set the enabletestclient attribute to true:

VaR Config = new httpconfiguration () {enabletestclient = true };

Then pass the httpconfiguration instance to the Configuration Attribute of httpservicehostfactory

Routes. Add (New serviceroute ("API/contacts", new httpservicehostfactory () {configuration = config}, typeof (contactsapi )));

Press F5 to start the debugging project, and then add/test to the browser.

Summary

Through this quick start, we learned the following content:

  • How to Use nuget to add web API reference to a project
  • How to create a web API accessed through HTTP GET
  • How to host a web API through Asp.net routes
  • How to access Web APIs through a browser or fiddler
  • How to enable odata URI query on APIs
  • How to Use the WCF Web Test client to test the WCF web API

You can get the code here.

Updated to webapi 0.5 preview on January 4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.