The ASP. NET MVC Web API Learning Note---the first Web API program---Recently, many large platforms have exposed the Web API

Source: Internet
Author: User



1. Web API Brief Description



Recently, many large platforms have exposed web APIs. such as Baidu map Web API, do map related people are familiar. Exposing the service this way makes it easy to integrate functionality with a wide variety of device and client platforms, and to create a richer HTML experience by using JavaScript in the browser. So I believe that the Web API will be more and more useful.



Say Web API Many people will think of web services, but they still have a certain difference: The Web API service is exposed through the general HTTP, rather than through a more formal service contract (such as soap)



2. Introduction to the ASP. NET Web API



Asp. NET Web API support allows you to easily create powerful Web APIs that can be accessed from a wide range of clients, including native applications using JavaScript from the browser to any mobile/client platform. It provides the following support:






(1) Modern HTTP programming Model : Directly accesses and processes HTTP requests and responds in your WEB application, using a clean, strongly typed HTTP object model. In addition to the programming model that supports this HTTP on the server, by using the new HttpClient API to invoke the Web API from any. NET application, we also support the same programming model in the client.



(2) Content negotiation : The Web API has built-in support for content negotiation-This enables the client and the server to work together to determine the correct data format to return from an API. We provide default support for JSON, XML, and form URL-encoded formats, and can extend this support by adding your own formatter, or even replace the default content negotiation policy with your own.



(3) query composition : The Web API through the OData URL convention makes it easy for you to support queries. When you return a type of IQueryable <T> from your Web API, the framework automatically provides it with OData query support-making it easy to page and sort.



(4) model binding and validation : Model binders provide an easy way to extract data from different parts of an HTTP request and convert that information part into a. NET object that can be used by Web API behavior. The Web API supports the same model bindings and ASP. NET MVC now supports the validation infrastructure.



(5) Routing : The Web ApI supports a complete set of routing features. Today's ASP. NET MVC and ASP. NET also supports this, including alignment parameters and constraints. By default, the Web API also provides a smart convention that allows you to easily create classes that implement a WEB API without having to apply attributes to your classes or methods. The configuration of the Web API is done purely by code-keeping your profile clean.



(6) Filters : The Web ApI makes it easy for you to use and create filters (for example: [authorization]) so you can encapsulate and apply cross-behavior.



(7) Improved testability: Instead of setting HTTP details in a static text object, use the Web API behavior with Httprequestmessage and Httpresponsemessage-two new HTTP objects (within others) makes testing easier. For example, you can unit test your Web ApI without having to use the Mocking framework.



(8) IOC support : Web API support by ASP. NET MVC implements a service locator pattern that enables you to resolve dependencies on different devices. You can easily integrate with an IOC container or a dependency injection architecture to maintain a clean dependency solution.



(9) Flexible hosting : Web APIs can be hosted on any type of ASP. NET application, including both application-based ASP. NET MVC and ASP. Web Forms). We also designed Web API support so that you can also choose to host/expose them within your own process if you do not want to use Asp.net/iis to do so. As for how and where you use it, this gives you the greatest flexibility.









3. Create a Web API program



Start VS2012 Create a new project, select the ASP. NET MVC4 Web API program in the installed template






In the ASP. NET MVC Project dialog box, select the Web API entry and click OK






After a successful creation, a Web API Service controller is automatically added to the project, with access to the address






Project solution, select the Models folder right-click to add a model class






The code is as follows:


Namespace Git.Framework.WebAPI.Models {public class ' contact ' {public int ID {get; set;}
public string Name {get; set;}
public string Sex {get; set;}
Public DateTime Birthday {get; set;}
public int Age {get; set;} } }





Engineering Solutions Select the Controllers folder right-click Add a new Web API controller






In the Add Controller Pop-up dialog box, select Template: Empty API Controller






Add the following code to the controller:


 namespace git.framework.webapi.controllers {    public class  Contactcontroller : apicontroller     {         Contact[] contacts = new Contact[]           {              new contact () {  Id=1, age=23, birthday=convert.todatetime ("1977-05-30"),  name= "Romance",  sex= "male",              new contact () { ID=2, Age=55,  Birthday=convert.todatetime ("1937-05-30"),  name= "Linghutao",  sex= "Man"},              new contact () { id=3, age=12, birthday= Convert.todatetime ("1987-05-30"),  name= "Guo Jing",  sex= "Male"},              new&nbsp Contact () { id=4, age=18, birthday=convert.todatetime ("1997-05-30"),  name= "Huang Rong",  Sex= "female "},         };
<summary>///api/contact//</summary>//<returns></returns>         Public ienumerable<contact> Getlistall () {return contacts; }
        /// <summary>          /// /api/contact/id         /// </summary>         /// <param name= "id" ></param>          /// <returns></returns>          public contact getcontactbyid (Int id)          {            Contact  Contact = contacts. Firstordefault<contact> (Item=>item.id==id);             if  (Contact == null)             {                 throw new httpresponseexception (Httpstatuscode.notfound);             }              return contact;         }
<summary>///Based on gender////api/contact?sex=///</summary>/<param N Ame= "Sex" ></param>///<returns></returns> public ienumerable<contact> GETLISTB Ysex (String sex) {return contacts. Where (item = Item.         sex = = sex); }     }}





4. Browser access to API path


Controller methed

Uri

Getlistall

/api/contact

Getlistbysex

"/api/contact?sex=" + Sex

Getcontactbyid

/api/contact/"+id





Browsing in IE browser has the following effect






If you browse in Chrome or FireFox, the following effect will be the first












5. JavaScript access to the Web API



Add a about view view to your project






The code is as follows:


@{Layout = null;}
<! DOCTYPE html>
            $ ("#btnID"). Click (function  ()  {                var  id = $ ("#txtID"). Val ();                 $.getjson ("/ api/contact/"+id, function  (data)  {                     var html =  "<ul>";                      $ (data). Each (function  (i, item)  {                         html +=   "<li>"  + item.ID +  ":"  + item. name +  ":"  +&nbSp;item. sex +  "</li>";                      });                      html +=  "</ul>";                      $ ("#contactID"). HTML (HTML);                 });             });
            $ ("#btnSex"). Click (function  ()  {                var  sex = $ ("#ddlSex"). Val ();                 $.getjson ("/ api/contact?sex= " + sex, function  (data)  {                     var html =  "< Ul> ";                      $ (data). Each (function  (i, item)  {                         html +=   "<li>"  + item.ID +  ":"  + item. name +  ":"  + item. sex +  "</li>";                      });                      html +=  "</ul>";                      $ ("#contactSex"). HTML (HTML);                 });             });         });     </script>











6. Web API Summary



1.Web API Controllers (Controller) inheritance Apicontroller



2. Api Url Map:api/{controller}/{id} Each "Action" is mapped through the HTTP verb (get/post/put/delete)



3. The client can specify the format of the returned data through the Http Header's Accept. The default is support: Appliction/xml and Application/json, when you want to return a picture format such as image/jpeg, you need to add mediatypeformatter. For example: When a task is specified, the picture information for the task is obtained by specifying ACCEPT:IMAGE/JPEG. (Detailed in the following sections)



The series about 20 articles, looking forward to your shooting bricks!






The ASP. NET MVC Web API Learning Note---the first Web API program---Recently, many large platforms have exposed the Web API


Related Article

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.