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="牙刷",ProductCategory="洗漱用品"},
                    new Product(){ ProductID="002", ProductName="《.NET框架设计—大型企业级应用框架设计艺术》", ProductCategory="书籍"}
                });
        }

        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 Side Service Listening is turned on");
                 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="Washing Supplies"},
                    New Product(){ ProductID="002", ProductName="".NET Framework Design - Large Enterprise Application Framework Design Art", ProductCategory="Book"}
                });
        }


        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();

            / / Get a list of goods information
            HttpResponseMessage responseMessage =
                Await httpClient.GetAsync("http://localhost/selfhost/api/product");
            IEnumerable<Product> products = await responseMessage.Content.ReadAsAsync<IEnumerable<Product>>();
            OutputProductInfo(products);


            //Add goods
            Product product = new Product()
            {
                ProductID = "003",
                ProductName = ""ASP.NET Web API 2 Framework Secret"",
                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 goods information
            responseMessage = await httpClient.GetAsync("http://localhost/selfhost/api/product/003");
            Product = (await responseMessage.Content.ReadAsAsync<IEnumerable<Product>>()).First();
            product.ProductCategory = "book";
            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 the specified goods
            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

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.