Example of ASP. NET Web API, asp. netapi

Source: Internet
Author: User
Tags webhost

Example of ASP. NET Web API, asp. netapi
Example of ASP. NET Web API opening

 

ASP. NET Web API

For my beginners, the ASP. NET Web API framework is unfamiliar and familiar.

ASP. NET Web API is a brand new framework. I am not very clear about the role this framework plays in a project. To tell the truth, it is not what I don't want but what I can do, you can only try to understand it yourself.

Familiar with ASP. NET Web APIs and ASP. net mvc frameworks seem similar at the beginning.

Let's just talk about it. Let's join me in learning ASP. NET Web API, a new framework.

 

Demo of ASP. NET Web API

Basic Environment Configuration

First, create a new class library project named "Common" and define the item information type. The sample code is as follows:

Code 1-1

namespace Common{    public class Product    {        public string ProductID { get; set; }        public string ProductName { get; set; }        public string ProductCategory { get; set; }    }}

CreateWebHostHost environment

Then we create an empty ASP. net web application is named WebHost, which describes ASP. NET Web API framework is only an independent framework, and it cannot run independently. Therefore, it needs the host environment, the newly created WEB application will temporarily carry ASP.. NET Web API framework.

 

 

Reference assembly

Newtonsoft. Json. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Packages \ Newtonsoft. Json.4.5.6 \ lib \ net40Newtonsoft. Json. dll

 

System. Net. Http. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Assemblies \ System. Net. Http. dll

 

System. Net. Http. Formatting. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Assemblies \ System. Net. Http. Formatting. dll

 

System. Web. Http. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Assemblies \ System. Web. Http. dll

 

System. Web. Http. WebHost. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Assemblies \ System. Web. Http. WebHost. dll

 

Common. dll (project reference)

Or use this reference method:

 

(If the directory location described above does not contain Newtonsoft. Json. dll, search for the file and reference it manually .)

Then we create a WebApplication ProcessingGlobl. asax and register the route in its Application_Start () method. The sample code is as follows:

Code 1-2

using System.Web.Http;namespace WebHost{    public class Global : System.Web.HttpApplication    {        protected void Application_Start(object sender, EventArgs e)        {            GlobalConfiguration.Configuration.Routes.MapHttpRoute(              "DefaultAPI", "api/{controller}/{id}", new { controller="product",id = RouteParameter.Optional });        }    }}

After the route is registered, we have to create a new Web API controller named ProductController. The sample code is as follows:

Code 1-3

Using System. web. http; using Common; namespace WebHost. controllers {public class ProductController: ApiController {private static List <Product> products; static ProductController () {products = new List <Product> (); products. addRange (new Product [] {new Product () {ProductID = "001", ProductName = "toothbrush", ProductCategory = "toiletries"}, new Product () {ProductID = "002", ProductName = "《. NET Framework Design-large enterprise application framework design art ", ProductCategory =" books "}});} public IEnumerable <Product> Get (string id = null) {return from product in products where product. productID = id | string. isNullOrEmpty (id) select product ;}}}

In code 1-3, we can see that the ProductController controller inherits from ApiController. Here, I guess it should be the same as ASP.. net mvc Framework processes the same controller. After the request arrives and the request is routed, the Web API framework searches for all referenced assemblies in the current project and finds the types inherited from ApiController and caches them in an xml file, I don't know if I guess it is true or not. Let's verify it later. Let's mention it here.

Careful friends may find that there is no corresponding Action route parameter during route registration. In fact, this is a difference between the Web API framework, it determines the Action Method Based on the Http request method. However, the default Request Method of the browser is Http-get, so we can directly run the project at this time.

Figure 2

 

CreateSelfHost

The following example shows how to use the ASP. NET Web API framework in the SelfHost host environment.

First, we create a new console application named SelfHost. The only difference between the Assembly reference of the SelfHost Environment Project and the WebHost project reference mentioned above is that the System. web. http. webHost. change the dll assembly to System. web. http. selfHost. dll assembly. The reference path remains unchanged. You can also add it using the extension bar in the reference.

 

Next let's take a look at what we need to do in SelfHost. First, we need to register the route. This is the first thing we do each time. The sample code is as follows:

Code 1-4

Using System. web. http; using System. web. http. selfHost; namespace SelfHost {class Program {static void Main (string [] args) {HttpSelfHostConfiguration selfHostConfiguration = new HttpSelfHostConfiguration ("http: // localhost/selfhost "); using (HttpSelfHostServer selfHostServer = new HttpSelfHostServer (selfHostConfiguration) {selfHostServer. configuration. routes. mapHttpRoute ("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter. optional}); selfHostServer. openAsync (); Console. writeLine ("Server Service listener enabled"); Console. read ();}}}}

Here is a brief description. In the example of the HttpSelfHostConfiguration object in code 1-4, the base address is set. For the HttpSelfHostConfiguration type, it is inherited from the HttpConfiguration type, and the HttpConfiguration type is an important type, most of the configuration information in the WebAPI framework is set in this type of instance. It will be mentioned later.

The HttpSelfHostServer object is a very important role in the SelfHost host environment. It is responsible for processing requests and other operations (because it is the "Leader" of the pipeline model of the WebAPI framework in the SelfHost environment "), here, we only need to know a little about it, and we will unveil its mysteries in the later section of the pipeline.

Next, we will see that the Routes attribute in the Configuration Attribute of the HttpSelfHostServer object instance provides the registration of Routes. This part will be explained in the routing section below.

Then we can see that we can open the service listener and wait for the request to be processed. (Here, the listener/Processing request is not to process the real request, but to process the encapsulated object of the request. The pipeline will be explained in detail)

 

After registering a route, we need to create a new Web API controller, just like the content in the WebHost section above. However, we need to slightly modify the Controller code here, the sample code is as follows:

Code 1-5

Using System. web. http; using Common; namespace SelfHost. controllers {public class ProductController: ApiController {private static List <Product> products; static ProductController () {products = new List <Product> (); products. addRange (new Product [] {new Product () {ProductID = "001", ProductName = "toothbrush", ProductCategory = "toiletries"}, new Product () {ProductID = "002", ProductName = "《. NET Framework Design-large enterprise application framework design art ", ProductCategory =" books "}});} public IEnumerable <Product> Get (string id = null) {return from product in products where product. productID = id | string. isNullOrEmpty (id) select product;} public void Delete (string id) {products. remove (products. first (product => product. productID = id);} public void Post (Product product) {products. add (product);} public void Put (Product product) {Delete (product. productID); Post (product );}}}

Several Action methods added by the Controller in code 1-5 also correspond to the Http request methods respectively. This is the basic function for adding, deleting, modifying, and querying. Then we need a client to access it.

 

CreateClinet

Create a console application named Clinet and add the following Assembly reference:

 

Newtonsoft. Json. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Packages \ Newtonsoft. Json.4.5.6 \ lib \ net40Newtonsoft. Json. dll

 

System. Net. Http. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Assemblies \ System. Net. Http. dll

 

System. Net. Http. Formatting. dll path: C: \ Program Files \ Microsoft ASP. NET \ ASP. net mvc 4 \ Assemblies \ System. Net. Http. Formatting. dll

 

Common. dll (project reference)

The following is an example of accessing resources in the SelfHost environment in the Client project. The sample code is as follows:

Code 1-6

Using Common; using System. net. http; namespace Client {class Program {static void Main (string [] args) {AsyncProcess (); Console. read ();} private async static void AsyncProcess () {HttpClient httpClient = new HttpClient (); // obtain the item information list HttpResponseMessage responseMessage = await httpClient. getAsync (" http://localhost/selfhost/api/product "); IEnumerable <Product> products = await responseMessage. content. readAsAsync <IEnumerable <Product> (); OutputProductInfo (products); // Add Product product = new Product () {ProductID = "003", ProductName = "ASP. NET Web API 2 Framework secrets ", ProductCategory =" food "}; await httpClient. postAsJsonAsync <Product> (" http://localhost/selfhost/api/product ", Product); responseMessage = await httpClient. GetAsync (" http://localhost/selfhost/api/product "); Products = await responseMessage. Content. ReadAsAsync <IEnumerable <Product> (); OutputProductInfo (products); // modify the specified Product information responseMessage = await httpClient. GetAsync (" http://localhost/selfhost/api/product /003 "); product = (await responseMessage. content. readAsAsync <IEnumerable <Product> ()). first (); product. productCategory = "books"; await httpClient. putAsJsonAsync <Product> (" http://localhost/selfhost/api/product ", Product); responseMessage = await httpClient. GetAsync (" http://localhost/selfhost/api/product "); Products = await responseMessage. Content. ReadAsAsync <IEnumerable <Product> (); OutputProductInfo (products); // Delete await httpClient. DeleteAsync (" http://localhost/selfhost/api/product /001 "); responseMessage = await httpClient. GetAsync (" http://localhost/selfhost/api/product "); Products = await responseMessage. content. readAsAsync <IEnumerable <Product> (); OutputProductInfo (products);} private static void OutputProductInfo (IEnumerable <Product> products) {foreach (Product product in products) {Console. writeLine ("ProductID: {0}, ProductName: {1}, ProductCategorm: {2}", product. productID, product. productName, product. productCategory);} Console. writeLine ("-------------------------");}}}

Many types in code 1-5 will be explained one by one in the subsequent sections. Here we will not elaborate on them, but will look at our final example results:

First, we need to run the SelfHost project, and wait for the interface and Example 3, and then the Client project to access the resources in SelfHost. Result 4:

Figure 3

Figure 4

References: http://www.cnblogs.com/artech/p/web-api-sample.html

I just simplified some adjustments based on the examples in Jiang's books, because this example is used later.

 

In the beginning, there were almost no books and materials for Web APIs in China. Of course, there were books from abroad, but they were all in English. For those who do not have a basic English language, I am so sorry. The only way to live is to look at it with a translation tool.

Fortunately, jiangda's new work has come out, or it is impossible to learn Web APIs. After reading the first three chapters, I have gained a lot of comprehensive knowledge points. I will write some of them later and share them with you.

 

Author: Jin Yuan

Source: http://www.cnblogs.com/jin-yuan/

The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and go to the Article Page.


I am a newbie in how to call web APIs and web services on a website created in C #. I hope to provide a detailed introduction or a tutorial.

Your api has never been seen before, so it is hard to say how to call it, but even if there is no ws or api, as long as the data on that terminal is displayed on its page, in theory, we can collect the data back. The principle is very simple. You can use your program to get the webpage code, and then analyze and extract the data you need in the code, baidu's c # website collection can be found in many examples.
 
How is web API implemented?

This is too broad. You can buy some basic books on your own.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.