ASP. NET MVC Web API Learning Note---the First WEB API program

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html

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= "Make Fox punch", sex= "male"},
New Contact () {id=3, age=12, Birthday=convert.todatetime ("1987-05-30"), name= "Guo Jing", sex= "male"},
New 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>
Search by gender
/api/contact?sex= Women
</summary>
<param name= "Sex" ></param>
<returns></returns>
Public ienumerable<contact> getlistbysex (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>
<meta name= "viewport" content= "Width=device-width"/>
<title>About</title>
<script type= "Text/javascript" src= "/scripts/jquery-1.7.1.min.js" ></script>
<script type= "Text/ecmascript" >
$ (document). Ready (function () {
$ ("#btnAll"). Click (function () {
$.getjson ("/api/contact", function (data) {
var html = "<ul>";
$ (data). Each (function (i, item) {
HTML + = "<li>" +item.id+ ":" +item. Name+ ":" +item. sex+ "</li>";
});
HTML + = "</ul>";
$ ("#contactAll"). HTML (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 + ":" + 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>
<body>
<p>
<input type= "button" id= "Btnall" value= "Query All"/>&nbsp;
</p>
<p>
<input type= "text" id= "txtID" name= "txtID"/>
<input type= "button" id= "Btnid" value= "Query by id"/>&nbsp;
</p>
<p>
<select id= "Ddlsex" name= "Ddlsex" >
<option value= "male" > Male </option>
<option value= "Women" > Women </option>
</select>
<input type= "button" id= "Btnsex" value= "Search by gender"/>&nbsp;
</p>
<div id= "Contactall" >
</div>
<div id= "ContactID" >
</div>
<div id= "Contactsex" >
</div>
</body>

Run results

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!

ASP. NET MVC Web API Learning Note---the First WEB API program

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.