WebApi learning a preliminary understanding and creation project

Keywords: Attribute JSON xml

WebAPI

I. definition of WebAPI

A framework for providing data to the front end

Restful data supply mode
Post submission data (added)
Get data (check)
Put modification data (modification)
Delete delete data
Common for the first two, these four represent the addition, deletion, modification and search.
However, some enterprises may only use Post and get. Get is used for query and Post is used for all addition, modification and deletion.

II. WebAPI creation

First, open vs. the version of VS I use here is Visual Studio 2017.
Create WebAPI

Select Web API and click OK
After creation, you can see that the project automatically generates project files based on MVC structure.
In general, web API only has Model and Controller. VS adds a prompt page View by default here.

Then directly press F5 to run, you will get a default page, click API.

There are four default request methods, Get Post Put Delete

This page corresponds to two Controllers under the Controllers folder in the project.
The default two controllers have different functions because of their different parent classes.

HomeController inherits from System.Web.Mvc.Controller
System.Web.Mvc.Controller is MVC controller.

 public class HomeController : Controller //MVC controller
    {
        public ActionResult Index()
        {
            ViewBag.Title = "Home Page";

            return View();
        }
    }

ValuesController inherits from System.Web.Http.ApiController
System.Web.Http.ApiController is a WebAPI controller.

  public class ValuesController : ApiController //API controller
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
        // POST api/values
        public void Post([FromBody]string value)
        {
        }
        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }

First look at the WebAPI controller. In the ValuesController, the code contains five default definition methods, including two get methods: one is request without parameters, the other is request with parameters.

 public class ValuesController : ApiController //API controller
   {
       // GET api/values system default configuration address
       public IEnumerable<string> Get() //Request with Get without parameters, program execution here
       {
           return new string[] { "value1", "value2" };
       }
       // GET api/values/5 system default configuration address
       public string Get(int id) //Request with parameters in Get, program execution here
       {
           return "value";
       }
       // Address of default configuration of POST api/values system
       public void Post([FromBody]string value) //Request as Post, program execution here
       {
       }
       // PUT api/values/5 address of system default configuration
       public void Put(int id, [FromBody]string value) //As a Put request, the program executes here
       {
       }
       // DELETE api/values/5 address of system default configuration
       public void Delete(int id)  //To Delete the request, the program executes here
       {
       }
   }

Next, set the breakpoint, F5 for debugging, and simulate the request test for verification.
Enter the address field given by default in the comment (that is, on the method / / GET api/values, this is the address of the default system configuration)

You can see that you enter the Get method and return a value1 and value2 in xml formatYou can see that you have entered the Get method with parameters and returned value.
Other request methods will not be listed one by one.
Here some friends will ask, the address of this API is the default of the system, so how can I modify it into a custom one? This will be explained later when the app start folder is introduced.
After understanding the WebAPI controller mechanism, let's customize a controller and feel the process.
Right click Controllers - click Add - select controller

Select WebAPI2 controller

Pop up the name of the Controller. Pay attention to the Default shadow part of the system here, which means that the system only allows us to modify the Default in the Default Controller. If we change the later Controller, the system will not recognize it.

I built a controller of Books, inherited from ApiController, which is a controller of WebAPI, and wrote a Get method.

 public class BooksController : ApiController //WebAPI controller
    {
     public string Get()
        {
            return "CLR Via C#";
        }
    }

Then the access test is performed.
Press F5 to start the project, and enter http://localhost:xxxxx... Here's a friend to ask, what should I enter after the port number in the address bar?
As mentioned above, the address written on the system default ValuesController controller note is / api/values, so the access address is: http://localhost: port number / api/values.
How to write the address of the new controller?
We notice that the "values" after the api / is the same as the name before the Controller class name Controller, so when the new Controller class name is BooksController, the access address is: http://localhost: port number / api/Books.
Enter address request:

The system returns the results returned in the above methods.
This is the result of a direct web request.

In order to verify the form of data in the process of practical request, we use http request to test this address. Here I use a free interface testing tool of basic version called PostMan. The download address is: https://www.getpostman.com
Enter the address for Get request, and it is found that the returned value is a value.

If the object returned in the get method is an object, what will you get when you make a specific request?
Create a new class MathBooks

public class MathBooks
    {
        /// <summary>
        ///Book number
        /// </summary>
        public string Id { get; set; }
        /// <summary>
        ///Book name
        /// </summary>
        public string Name { get; set; }
     
    }

Change the original Get request to

 public MathBooks Get()
        {
            return new MathBooks(){ Id = "1", Name = "Differentiation of univariate function" };
            //return "CLR Via C#";
        }

Operation request

You can see that an array is returned.
If it's a List object, test what to return.

public List<MathBooks> Get()
        {
            return new List<MathBooks>()
            {
            new Models.MathBooks() { Id = "1", Name = "Limit and continuity"},
            new Models.MathBooks() { Id = "1", Name = "derivative and differentiate "},
            new Models.MathBooks() { Id = "2", Name = "Differential mean value theorem and application of derivative"},
            new Models.MathBooks() { Id = "3", Name = "Indefinite integral"},
            new Models.MathBooks() { Id = "4", Name = "Definite integral and abnormal integral"},
            new Models.MathBooks() { Id = "5", Name = "double integral"}
            };
            //return "CLR Via C#";
        }

It returns a Json array object, which shows that WebApi will automatically serialize any customized return type, string, object, etc.

3. WebAPI routing control

As mentioned above, how the api in / api/values in the address bar changes to custom. With this problem in mind, we are looking for a file called app start in the project.

Here are two classes called RouteConfig and WebApiConfig.
RouteConfig is the router of MVC.

   public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home",
                 action = "Index", id = UrlParameter.Optional }
            );
        }

WebApi config is the router of WebApi.

  public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routing
            config.MapHttpAttributeRoutes();
            /*This is a configuration set that configures multiple routes. By default, it consists of name, RouteTemplate, and Defaults. Here is a mapping.
            HttpRoute,name Represents the route name. Its current name is DefaultApi. Its name cannot be duplicate in a project's route set. 
            routeTemplate It represents the routing template. It is an address definition rule. Why add an API to the address bar?
            Because it's defined here.
            If you change the / / api to a custom one, the address accessed during generation will also be redefined, where {controller} is the controller name.
            {id}It is a parameter. The id set in defaults is routeparameter.optional, which means optional parameter. It is optional.*/
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

There is a {id} in the above routing template, which is the ID parameter added to the back address when calling the get with parameter form in the previous address. /api/values/12345 id is the value behind values.
At this point, we will add another Get method to the WebApi controller.

 public class BooksController : ApiController//WebAPI controller
    {
        public List<MathBooks> Get()
        {
            return new List<MathBooks>()
            {
            new Models.MathBooks() { Id = "1", Name = "Limit and continuity"},
            new Models.MathBooks() { Id = "1", Name = "derivative and differentiate "},
            new Models.MathBooks() { Id = "2", Name = "Differential mean value theorem and application of derivative"},
            new Models.MathBooks() { Id = "3", Name = "Indefinite integral"},
            new Models.MathBooks() { Id = "4", Name = "Definite integral and abnormal integral"},
            new Models.MathBooks() { Id = "5", Name = "double integral"}
            };
            //return "CLR Via C#";
        }

        public string Get(string BookName) //To add a method to find the title of a book, you need to pass in the BookName parameter, which is defined as the parameter.
        {
            return "The title of the book you are looking for is:"+BookName;
        }
    }

At this time, when accessing the address bar, you should enter http://localhost:xxxxx/api/books/?BookName=1. Enter the defined bookname parameter after books in the form of? Parameter = XXX. In the address bar, '?' represents the query string.
Note: if the Attribute is not specified before the method name defined in the controller, the Get/Post/Put/Delete prefix cannot be removed, otherwise it cannot be booted. This is a custom constraint of the project and will be booted according to the method name. If the method name is written as search book without specifying Attribute, it cannot be accessed. You need to write it as getsearch book, or add [HttpGet]/[HttpPost] to the method name for effective access.

	    [HttpGet] //Specify Attribute here to remove the Get/Post/Put/Delete prefix
        public string Search_Book(string book)
        {
            return "The title of the book you are looking for is:" + book;
        }

Then create a Post method to verify the Post request

    public string PostUpdate(MathBooks mb)
        {
            return "The updated book number received is:"+mb.Id+"The title of the book is:"+mb.Name;
        }

Enter the address in PostMan, switch to Post mode, click body, click raw, switch to Json mode, and enter Json string.

Results returned successfully
What if multiple parameters are passed?

   public string PostUpdate(int id,string BookName,string bookStore,MathBooks mb)
        {
            return "The updated book number received is:"+mb.Id+"The title of the book is:"+mb.Name;
        }

Now you need to pass in an id, a BookName, a bookStore, and an object. How can I request it?
First, the defined Id is used as an optional parameter for routing control, directly after the address / + parameter. The parameters of BookName and bookStore need to use the above mentioned query string? + parameter name = parameter form, involving multiple parameters using & & to connect.
http://localhost:xxxxx/api/Books/1?BookName = math book & & BB = 123
The whole request string is generated, and then the last MathBooks object is filled in for Post request.

Results return results.

Posted by cyberplasma on Fri, 25 Oct 2019 03:31:06 -0700