Web API Strong Getting Started Guide

Source: Internet
Author: User
Tags baseuri actionlink

    • Absrtact: Webapi is a relatively broad concept. Here we refer to Webapi specifically Asp.netwebapi. In this article we mainly describe the main functions of WEBAPI and the comparison with other types of frameworks, and finally, some relatively complex examples show how to build HTTP services through WEBAPI, while also demonstrating the various strengths of VisualStudio building. NET projects. Directory What is WEBAPI why do you want to use WEBAPI features WEBAPIVSMVCWEBAPIVSWCFWEBAPI integrated MONGODB involves technical services Uripattern prepare work code implementation What is WEBAPI official definition as follows
    • Tags: API Web

The Web API is a relatively broad concept. Here we mention that the Web API specifically refers to the ASP.

In this article we mainly describe the main features of the Web API and the comparison with other types of frameworks , and finally, some relatively complex examples show how to build HTTP services through the Web API , while also showing the visual Studio builds a variety of powerful. NET projects.

    • What is a Web API
    • Why use the Web API
    • Feature Introduction
    • Web API vs MVC
    • Web API vs WCF
    • Web API Integration MongoDB
      • Technology involved
      • Service URI Pattern
      • Preparatory work
      • Code implementation

The official definition is as follows, highlighting the two key points that can be interfaced to various clients (browsers, mobile devices), to build the HTTP service framework.

The ASP. NET Web API is a framework for this makes it easy-to-build HTTP services that reach a broad range of Clients, including browsers and mobile devices. The ASP. Ideal platform for building RESTful applications on the. NET Framework.

The WEB API positions itself in the ASP. NET Framework, with SIGNALR as the framework for building service. The Web API is responsible for building HTTP general Services, while SINGALR is primarily responsible for building real-time services such as stocks, chat rooms, online games, and more in real-time requirements.

The most important thing about Web APIs is the ability to build services for a variety of clients. In addition to the WCF REST Service, the Web API uses various aspects of the HTTP protocol to express services (such as uri/request response header/caching/versioning/content format). Therefore, many configurations are omitted.

When you encounter these situations, you can consider using the Web API.

    • Requires a Web service but does not require soap
    • Need to establish non-soap-based HTTP service on the basis of existing WCF services
    • Just want to publish some simple HTTP service, do not want to use the relatively complex WCF configuration
    • The published service may be accessed by a bandwidth-constrained device
    • Want to use the open source framework, when it is critical to debug or customize the framework

Key features of the Web API

1. Support for CRUD (create, retrieve, update, delete) operations based on HTTP verb (GET, POST, PUT, delete)

The different meanings are expressed by different HTTP actions, so there is no need to expose multiple APIs to support these basic operations.

2. The requested reply expresses a different meaning through the HTTP Status code, and the client can negotiate the format with the server via the accept header, such as whether you want the server to return JSON format or XML format.

3. The requested reply format supports Json,xml and can be extended to add additional formats.

4. Native support for OData.

5. Support Self-host or IIS host.

6. Support for most MVC features, such as Routing/controller/action Result/filter/model builder/ioc container/dependency Injection.

You might think that Web APIs are very similar to MVC, and what are the differences between them? First, this is their biggest difference.

To point out their differences in detail,

    • MVC is primarily used to build web sites that care about data as well as page presentation, while Web APIs focus only on data
    • The WEB API supports format negotiation, and clients can notify the server of the desired format via the Accept header
    • Web API Support Self HOST,MVC not currently supported
    • The Web API expresses different actions (CRUD) through different HTTP verb, and MVC expresses the action by the action name
    • The Web API is built into the ASP. Net System.Web.Http namespace, MVC is located under the System.Web.Mvc namespace, so features such as model binding/filter/routing are different
    • Finally, the Web API is ideal for building mobile client Services

What is the choice between the Publishing service and the Web API and WCF? Here are a few simple rules to judge,

    • If the service needs to support one-side messaging/message queue/duplex communication, select the WCF
    • If the service requires tcp/named PIPES/UDP (WCF 4.5), select the WCF
    • If the service needs to be on the HTTP protocol, and you want to take advantage of the various features of the HTTP protocol, select the Web API
    • If the service needs to be called by various clients (especially mobile clients), select the Web API

Asp. NET Web site has a lot of simple examples of Web API, look at the map and instance code you know how to use it. Here we demonstrate the functionality of the Web API with a slightly more complex example.

Technology involved

Used in our example:

    • Mongo DB Database saving data (NoSQL, Document Store, cross-platform, cross-language)
    • WEB API provides data services
    • MVC for Data presentation
    • Knockoutjs dynamic binding of client data, here is a simple introduction
Service URI Pattern

Action Http verb URI Get contact list get/api/contacts get filtered contacts get/api/contacts? $top =2 Get contact by ID get/api/contacts/id C reate new Contact Post/api/contacts Update a contact put/api/contacts/id Delete a contact delete/api/contacts/id

Preparatory work

1. Download and install MONGO DB, step to see here.

2. Mongo DB C # driver download can search for mongocsharpdriver in NuGet.

3. If you want to view the contents of the database locally, download Mongovue.

4. Knockoutjs download can search for Knockoutjs in NuGet.

Code implementation

1. Create a project

Create MVC4 WEB Application

Select the Web API in project template

Then the project is created, and controllers has a valuescontroller, which is the simplest web API Controller that is automatically generated.

As we said earlier, the System.Web.Http namespace is quoted.

2. Create model

Add contact class to model

The code is as follows, where Bsonid needs mongocsharpdriver.

Class= "BRUSH:CSHARP;" >public class Contact    {        [Bsonid] public        string Id {get; set;}        public string Name {get; set;}        public string Phone {get; set;}        public string Email {get; set;}        Public DateTime lastmodified {get; set;}    }

We need to add mongosharpdriver.

In addition, we need to add Repository,controller to the model to access MONGO DB through this class.

Public interface Icontactrepository {         IEnumerable getallcontacts ();         Contact GetContact (string id);         Contact Addcontact (contact item);         BOOL Removecontact (string id);         BOOL Updatecontact (string ID, contact item);       }

The complete implementation of Contactrepository is as follows,

public class Contactrepository:icontactrepository {mongoserver _server = null;        Mongodatabase _database = null;        Mongocollection _contacts = null; Public contactrepository (string connection) {if (string.            Isnullorwhitespace (Connection)) {connection = "mongodb://localhost:27017"; } _server = new mongoclient (connection).            Getserver (); _database = _server.            Getdatabase ("Contacts"); _contacts = _database.            GetCollection ("Contacts"); Reset database and add some default entries _contacts.            RemoveAll ();                    for (int index = 1, index < 5; index++) {Contact Contact1 = new Contact { Email = string. Format ("test{0} @example. com", index), Name = string. Format ("test{0}", index), Phone = string. Format ("{0}{0}{0} {0}{0}{0} {0}{0}{0}{0}", index)};            Addcontact (CONTACT1); }} public IEnumerable getallcontacts () {return _contacts.        FindAll ();            Public contact GetContact (string id) {imongoquery query = Query.eq ("_id", id); Return _contacts. Find (query).        FirstOrDefault (); Public contact Addcontact (Contact item) {Item. Id = Objectid.generatenewid ().            ToString (); Item.            LastModified = Datetime.utcnow; _contacts.            Insert (item);        return item;            } public bool Removecontact (string id) {imongoquery query = Query.eq ("_id", id); Writeconcernresult result = _contacts.            Remove (query); return result.        documentsaffected = = 1;            } public bool Updatecontact (string ID, contact item) {imongoquery query = Query.eq ("_id", id); Item.            LastModified = Datetime.utcnow;    Imongoupdate update = Update            . Set ("Email", item.) Email). Set ("LastModified", Datetime.utcnow). Set ("Name", item.) Name). Set ("Phone", item.)            Phone); Writeconcernresult result = _contacts.            Update (query, update); return result.        updatedexisting; }    }

3. Add Controller

Right-click Controllers Directory Select Add Controller

Select the empty API controller and name the controller Contactscontroller

Add the following code to see that the API method name in the controller is named after the HTTP verb.

public class Contactscontroller:apicontroller {private static readonly icontactrepository _contacts = new Con Tactrepository (String.        Empty); Public IQueryable Get () {return _contacts. Getallcontacts ().        AsQueryable (); The Public contact Get (string id) {Contact contact = _contacts.            GetContact (ID);            if (contact = = null) {throw new httpresponseexception (Httpstatuscode.notfound);        } return contact; Public contact Post (contact value) {Contact contact = _contacts.            Addcontact (value);        return contact; The public void is Put (string ID, contact value) {if (!_contacts.            Updatecontact (ID, value)) {throw new httpresponseexception (Httpstatuscode.notfound); }} public void Delete (string id) {if (!_contacts.     Removecontact (ID)) {           throw new Httpresponseexception (Httpstatuscode.notfound); }        }    }

4. Add View

First add the Knockoutjs library,

KNOCKOUTJS implements Dynamic HTML binding data through the MVVM pattern, where View-model is the model data saved by the client's JavaScript object.

First open the HomeController and add a new action code as follows, because we want to add the corresponding view to Contactscontroller in MVC.

Public ActionResult Admin ()        {            string apiuri = Url.httprouteurl ("Defaultapi", new {controller = "contacts",}); 
   viewbag.apiurl = new Uri (Request.url, Apiuri). Absoluteuri.tostring ();            return View ();        }

Then right-click the Admin method and select Add View

Select Create strongly-typed view to select the contact class in the model class.

Add the full code for the view, note that in view we access the Webapi via JS, and the data is rendered on the Web page by dynamic binding.

@model webapidemo.models.contact@{viewbag.title = "Admin";} @section Scripts {@Scripts. Render ("~/bundles/jqueryval") <script type= "Text/javascript" src= "@Url. Content (" ~/  Scripts/knockout-2.3.0.js ")" ></script> <script type= "Text/javascript" > Function Productsviewmodel ()          {var = this;          Self.products = Ko.observablearray ();          var BaseUri = ' @ViewBag. Apiurl ';              Self.create = function (formelement) {//If valid, post the serialized form data to the Web API              $ (formelement). Validate ();                      if ($ (formelement). Valid ()) {$.post (BaseUri, $ (formelement). Serialize (), NULL, "JSON")              . Done (function (o) {Self.products.push (o);}); }} self.update = function (product) {$.ajax ({type: "PUT", Url:baseuri + '/' + product.i          D, data:product}); } self.remove = function (product) {//First Remove from the server and then from the UI $.ajax ({type: "DELETE", Url:baseuri + '/' + product.          Id}). Done (function () {self.products.remove (product);});      } $.getjson (BaseUri, self.products);      } $ (document). Ready (function () {ko.applybindings (New Productsviewmodel ()); }) </script>}

Next, add a link to the admin page in _layout.cshtml as follows

<ul id= "Menu" >    <li> @Html. ActionLink ("Home", "Index", "Home", new {area = ""}, NULL) </li>    <li> @Html. ActionLink ("API", "Index", "help", new {area = "}, NULL) </li>    <li> @Html. ActionLink (" Admin "," admin "," Home ") </li> </ul>

5. Testing and Commissioning

Done, directly run our work, our admin link is also shown in the top right corner,

The admin page looks like, the contact list is dynamically loaded in, can be added through this page, modify, delete the operation.

View the request content via IE network capture.

Reload the page, you can see the format of the reply is JSON,

JSON content is some of the data we mock.

Next we modify, delete, and add a record, you can see the use of different HTTP method.

I am gratified to see the data of the next DB by the Mongovue installed above, and the user who was added first.

In fact, there are two interesting examples, but the article is long, sorry to delay everyone time, had to put on, and then write.

Web API Strong Getting Started guide

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.