1. Introduction

With the development of Web technology, now a variety of frameworks, front-end, back-end, countless. The pressure on full-stack engineers is mounting. The development of PC terminal, pad terminal and mobile terminal App (Android /IOS) makes the development mode of integrating the front and back terminals very cumbersome. Therefore, the front and back end separation is the development trend of the web, where RESTful API is currently the best practice of front and back end separation, ASP.NET web API is in. NET Framework ideal platform for building RESTful applications. The Web API application is shown in the following figure.

2.ASP.NET Web API Introduction

ASP.NET Web API is a framework that makes it easy to build HTTP services across a wide range of clients, including browsers and mobile devices. ASP.NET Web API is in. NET Framework ideal platform for building RESTful applications. In REST, GET,POST,PUT and DELETE are used to add, DELETE, modify, and query data. If a developer’s application complies with RESTful principles, its service is called “RESTful application service “.

The ASP.NET Web API core message processing pipeline is independent of the ASP.NET platform. It is more complex and powerful than the pipeline designed by ASP.NET MVC. It supports Web Host and Self Host (any type of application, Such as console, Windows Form application, WPF application and even Windows Service). This article mainly introduces the first method. The entire Web API life cycle is shown in the following figure.

3. Manually build the basic framework

Visual Studio provides a project template specifically for creating ASP.NET Web API applications. With the wizard provided by this project template, you can create a complete ASP.NET Web API project in one click. During project creation,Visual Studio automatically adds the necessary assembly references and configuration, and even generates the relevant code for us. In short, this wizard-generated project is an executable application in its own right once it is created. Instead of demonstrating the automatic creation process, I’ll focus on manual scaffolding, which will give us a deeper understanding of how Web APIS work.

(1) Create an empty ASP.NET Web application

In VS2017, select ASP.NET Web application (.net Framework), Framework select. NET Framework4.5, as shown below.

Select the empty project and remove the MVC and Web API options, as shown below.

(2) download and install Microsoft.Asp.Net.Api via NuGet

Right click the project, select “Manage NuGet package”, search WebAPI, select Microsoft.Asp.Net.Api, click the “Install” button on the right to complete the installation, as shown below.

(3) Add the Global application class global.asax

Right-click the project, add the New item, and select the Global application class, as shown below.

Global.asax is a text file that provides globally available code. This code includes the application’s event handlers as well as session events, methods, and static variables. This file is sometimes referred to as an application file. Open the file with the code shown below and find that it contains the Web application entry Application_Start, which is similar to the main function of the WinForm application.

namespace MyWebAPI
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}
Copy the code

(4) Register Web API routing

The routing system is the first barrier for request messages to enter the ASP.NET Web API message processing pipeline, and its fundamental purpose is to parse URL requests, which will be covered in more detail than here in a future series of articles.

Register the Web API route in the Application_Start function as follows:

 protected void Application_Start(object sender, EventArgs e)
 {
     GlobalConfiguration.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional });
 }   
Copy the code

(5) Add a Web API controller

Right-click the project, add the New item, and select the Web API Controller class, as shown below.

If you open the valuesController.cs file, you will find that this class directly inherits from ApiController and contains actions such as GET,POST,PUT and DELETE, as shown below. The controller will be explained in detail in future articles, but not here.

public class ValuesController : ApiController
{
    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    public void Delete(int id)
    {
    }
}
Copy the code

(6) Call Web API

To run the program (automatically create IIS service), in the address bar enter http://localhost:52317/api/Values call the Get () method of the ValuesController, Google browsing shows the invocation of the results are shown below.

4. To summarize

At this point, the basic introduction of ASP.NET Web API and the detailed steps of manually building the basic framework of Web API are completed. Through this blog readers can be more in-depth understanding and understanding of Web API, if there are shortcomings in the article, but also hope to forgive, blog writing is not easy to hope for more support, the follow-up will update more content, interested friends can add attention, welcome message exchange! In the meantime, please scan the wechat official account below to get more dry goods!!