Introduction to ASP.NET Web API

Keywords: ASP.NET Front-end api RESTful

With the increasing complexity of the project, the data interaction of various third-party systems is becoming more and more frequent. It is inevitable to use Web API interface. Here, Web API is a relatively broad concept. This article refers to Web API, especially ASP.NET Web API. With some simple examples, this paper briefly describes the basic knowledge of ASP.NET Web API, which is only for learning and sharing. If there are deficiencies, please correct them.

What is RESTful?

The full name of REST is representative state transfer, which means state transfer in Chinese. REST itself does not create new technologies, components or services, but the idea behind RESTful is to use the existing features and capabilities of the Web and better use some guidelines and constraints in the existing Web standards.   If an architecture conforms to the constraints and principles of REST, we call it RESTful architecture. The original author described RESTful in this way [the purpose of my article is to understand and evaluate the architecture design of network-based application software on the premise of conforming to the architecture principle, so as to obtain an architecture with strong function, good performance and suitable for communication.]

Based on the above explanations, let's summarize what a RESTful architecture is:

  1. Each URI represents a resource;
  2. Between the client and the server, transfer some kind of presentation layer of this resource;
  3. The client operates the server-side resources through four HTTP verbs to realize "presentation layer state transformation".

What is a Web API?

ASP.NET Web API is based on C# building a secure REST style API. Through the ASP.NET Web API, you can quickly create services called on various clients, including Web browser and mobile. As follows:

Why use web APIs?

ASP.NET Web API is a framework that can be easily built to achieve a wide range of HTTP service clients, including browsers and mobile devices. The. NET framework is an ideal platform for building RESTful applications. Its position in the system architecture is as follows:

Create an ASP.NET Web API project

File -- new -- project open the [create new project] window, select [ASP.NET Web application (. NET Framework)], and click next, as shown below:

  Enter the [configure new project] window, enter the project name, select the project saving path, and then click [create], as shown below:

   Enter [create new ASP.NET Web application], select [empty], add [MVC,Web API] core reference, and then click [create], as shown below:

  Wait a moment, and the project will be created successfully. The directory structure is as follows:

  • App_ RouteConfig.cs in the start directory is the MVC core reference, which is mainly used to register MVC routing configuration
  • App_ WebApiConfig.cs in the start directory is the core reference of the Web API, which is mainly used to register the routing configuration of the Web API.
  • By default, three directories, Controllers, Models and Views, are created to store the contents of the three-tier architecture.

  Create the first interface

In the Controllers folder, right-click add Web API controller class, as shown below:

  Then enter the Controller name, ending with Controller, and click OK, as shown below:

  The controller created through the template automatically adds sample code, and inherits ApiController by default, as shown below:

namespace WebApiDemo.Controllers
{
    public class StudentController : 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)
        {
        }
    }
}

  Custom API

To test, first create a new Model class Student, as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebApiDemo.Models
{
    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public bool Sex { get; set; }
    }
}

1. GET mode

In the StudentController, reference the Student model in the Models namespace and modify the Get method as follows:

By default, the WebApi template automatically creates two Get methods, one with no parameters and the other with parameters. They return the list and specific instances respectively, adjust them, and return Student data, as shown below:

// GET api/<controller>
public IEnumerable<Student> Get()
{
      return new Student[] { new Student() {
           Id=1,
           Name="Alan.hsiang",
           Age=20,
           Sex=true
       }, new Student() {
           Id=2,
           Name="Json.hsiang",
           Age=18,
           Sex=false
        } };
}

// GET api/<controller>/5
public Student Get(int id)
{
      return new Student()
       {
            Id = 1,
            Name = "Alan.hsiang",
            Age = 20,
            Sex = true
        };
}

Then run visual studio, the default port is 44311, and test through PostMan.

Return the Student list without parameters. As follows:

  With parameters, a specific Student instance is returned, and the id can be passed through api/Controller/id. As follows:

2. POST mode

The POST method is mainly submitted through the body form. In this example, modify the self-contained code, receive the Student instance and return the Student string, as shown below:

// POST api/<controller>
public string Post([FromBody] Student value)
{
      return string.Format("Student ID={0},full name={1},Age={2},Gender={3}",value.Id,value.Name,value.Age,value.Sex);

}

Access through Postman. Select POST as the access method, raw as the Body, and JSON as the data format, as shown below:

3. PUT mode

PUT mode is generally used to modify data. In this example, for testing, the received ID is returned as follows:

// PUT api/<controller>/5
public int Put(int id, [FromBody] string value)
{
      //For testing, return the received id
      return id;
}

Test through Postman. Select PUT as the request method. If there is only one string type parameter for the Body content, the parameter name is empty, as shown below:

4. DELETE mode

The DELETE method is generally used to DELETE data. In this example, a string is returned for testing, as shown below:

// DELETE api/<controller>/5
public string Delete(int id)
{
      return string.Format("Id={0} Deleted", id);
}

Test through Postman, and select DELETE as the request method, as shown below:

  summary

Through the test of the above example, it is summarized as follows:

  • The access path conforms to the RESTful style, and the specific functions are distinguished by request, as shown below:
    • GET request list: https://localhost:44311/api/Student
    • GET request single instance: https://localhost:44311/api/Student/1
    • POST request: https://localhost:44311/api/Student/
    • PUT mode: https://localhost:44311/api/Student/3
    • DELETE mode: https://localhost:44311/api/Student/4
  • Request data format:
    • GET mode, which generally passes parameters in the form of URL
    • POST, PUT and DELETE mode, using body to transfer parameters, and the format is generally JSON.

Through the above summary, it is found that the web API coincides with the RESTful style architecture.

Multiple parameters in the same way

In this example, if there are multiple GET request methods with different parameter formats and numbers, how to match them is as follows:

// GET api/<controller>
public IEnumerable<Student> Get()
{
      return new Student[] { new Student() {
           Id=1,
           Name="Alan.hsiang",
           Age=20,
           Sex=true
        }, new Student() {
           Id=2,
           Name="Json.hsiang",
           Age=18,
           Sex=false
        } };
}

// GET api/<controller>/5
public Student Get(int id)
{
     return new Student()
     {
          Id = 1,
          Name = "Alan.hsiang",
          Age = 20,
          Sex = true
       };
}

// GET api/<controller>/5?name=aabbcc
public Student Get(int id,string name)
{
      return new Student()
      {
           Id = id,
           Name = name,
           Age = 22,
           Sex = true
        };
}

The first two methods are tested through Postman, and now the third method is tested as follows:

Same way, different names  

From the above example, we can see that the method name and the request method correspond one-to-one. What if the method name and the request method are inconsistent?

  First, add the GetStudent method. In order to distinguish, write 0 and 1 in the returned Name value respectively, as shown below:

// GET api/<controller>/5?name=aabbcc
public Student Get(int id,string name)
{
        return new Student()
        {
            Id = id,
            Name = name+"---0",
            Age = 22,
            Sex = true
         };
}

public Student GetStudent(int id, string name)
{
       return new Student()
       {
            Id = id,
            Name = name+"---1",
            Age = 22,
            Sex = true
        };
}

Open Postman to test, and directly report an error. It is said that two resources matching the format have been found, as shown below:

  For the above problems, you can find that the routeTemplate injected by WebApi is api/{controller}/{id}, which is different from MVC. WebApi registers the default routing template as follows:

namespace WebApiDemo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routing
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Route properties

In order to solve the problem that the two access methods are the same, the parameters are the same, but the method names are different, which will lead to acquisition errors, WepApi introduces the routing feature, as shown below:

[Route("api/Student/QueryStudent/{id}")]
[HttpGet]
public Student QueryStudent(int id, string name)
{
     return new Student()
     {
          Id = id,
          Name = name + "---1",
          Age = 22,
          Sex = true
     };
}

As follows, you can access it normally through Postman. Default access Get(int id,string name)

  Through the routing feature, access / api/Student/QueryStudent/4?name=HEX, as follows:

Routing prefix  

The routing feature perfectly solves the problem that one Controller accesses two different methods in the same way at the same time. However, if the full name of each routing feature is written, it will be cumbersome and error prone, so the routing prefix came into being.

The routing prefix modifies the Controller and the routing feature modifies the Action, as shown below:

namespace WebApiDemo.Controllers
{
    [RoutePrefix("api/Teacher")]
    public class TeacherController : ApiController
    {
        public string Get(int id, string name) {
            return string.Format("[Get]Teachers looking for id={0},full name={1}", id, name);
        }

        [Route("query/{id}")]
        [HttpGet]
        public string QueryTeacher(int id, string name) {
            return string.Format("[Query]Teachers looking for id={0},full name={1}", id, name);
        }
    }
}

In this way, it can be distinguished when accessing. The default access to Get method is as follows:

  Access the Query method through the routing feature, as shown below:

  remarks

The above is a brief introduction to the basic knowledge of ASP.NET Web API. This paper aims to attract jade, learn together and make progress together.

Qingpingdiao · one                Li Bai  〔 Tang Dynasty]

Clouds think of clothes, flowers think of looks, spring breeze blows the sill, and dew is thick. If we hadn't met at the head of Qun Yushan, we would meet at the foot of the moon at Yaotai.

Qingpingdiao II               Li Bai  〔 Tang Dynasty]

A bright dew and a fragrant fragrance, clouds and rain, Wushan in vain. Ask who is in the Han Palace. Poor Feiyan leans on her new makeup.

Qingpingdiao · Qi3               Li Bai  〔 Tang Dynasty]

Famous flowers bring joy to the country, and the king looks at them with a smile. Explain that the spring breeze has infinite hatred, and the Chenxiang Pavilion leans against the appendix in the north.

Posted by macpaul on Sun, 07 Nov 2021 11:09:11 -0800