Web API Interface Design (learning)

Source: Internet
Author: User
Tags tojson

1. Determine the Get or post mode of MVC in the interface definition

Since our entire Web API platform is based on the development of the API on the basis of MVC, the interface of the entire Web API, when defined, generally needs to be displayed to declare that the interface is [HttpGet] or [HttpPost], although some interfaces may not be declared, However, it is also advantageous to avoid the following error messages, which are explicitly declared.

The requested resource does not support the HTTP method "POST

For example, the Lookup object interface defined in the base class is shown below.

        <summary>///        query the database to see if there is an object of the specified ID///</summary>//        <param name= "id" > Object ID value </ Param>        //<returns> Presence returns the specified object, otherwise returns null</returns>        [HttpGet] public        virtual T FindByID ( String ID, string token)

If the interface is added and deleted, it is generally necessary to declare the data for post, and for security reasons, more parameters need to be carried.

        <summary>////Insert the specified object into the database///</summary>//        <param name= "Info" > The specified object </param >///        <returns> Whether the operation was successful. </returns>        [HttpPost] public        virtual Commonresult Insert (T info, string token, string signature, string Timestamp, string nonce, String AppID)
2. Interface definition of dynamic object

In the General Web API interface, we may encounter many simple types of parameters, but also want them to post the data, then we can have two methods to deal with, one is to define a class to place these parameters, one is to use dynamic jobject parameters, The former has many inconvenient places because it is not possible to define more than one entity class for each interface parameter, so there may be many class definitions that are difficult to manage. As the following is the API invocation interface case, we also need to set such a processing rule.

Interface Call Request Description HTTP request mode: POST (use HTTPS protocol) https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_ Tokenpost data format: JSONPost Data example: {"group": {"id": 108, "name": "Test2_modify2"}}

So we're using jobject, so let's look at the definition of the interface and the processing code. Jobject is an object under the Newtonsoft.Json.Linq namespace.

//<summary>//Modify user password///</summary>//<param name= "param" > include user Compound objects for name and UserPassword </param>//<param name= "token" > User access token </param>//<returns>&         lt;/returns> [ HttpPost ] public commonresult modifypassword (jobject param, string token)            {//token check, non-pass throws exception Checkresult Checkresult = Checktoken (token);             dynamic obj = param;                 if (obj! = null) {string userName = Obj.username;                string userpassword = Obj.userpassword; BOOL success = Bllfactory<user>.                Instance.modifypassword (UserName, UserPassword);            return new Commonresult (success);            } else {throw new Myapiexception ("error passing parameter"); }        }
when we convert the Jobject object to the object we need, because we do not define a specific entity class, we use the dynamic syntax, which declares that this is a dynamically-based object that gets the corresponding property from the runtime.
Dynamic obj = param;

This allows us to invoke the JSON object of the dynamic post to the Web API interface, without having to pre-define the classes of the various interface parameters.

        <summary>///        Invoke Web API interface, modify user password///</summary>//        <param name= "userName" > User name </param>//        <param name= "UserPassword" > Modified password </param>//        <returns> If the modification returns true successfully, Otherwise returns false</returns> public        bool Modifypassword (string userName, string userpassword)        {            var action = "Modifypassword";            var postdata = new            {                userName = userName,                userpassword = UserPassword            }. ToJson ();            String url = Gettokenurl (action);            Commonresult result = Jsonhelper<commonresult>. Convertjson (URL, postdata);            return (result = null)? Result. Success:false;        }
The Gettokenurl is to build a complete submission address based on parameters such as token and API address. We pass the code above
            var postdata = new            {                userName = userName,                userpassword = UserPassword            }. ToJson ();

It is possible to create an object dynamically, generate its JSON string, submit the data post to the corresponding API interface, and then convert the object to the result, even if it is done.

3. Processing of collections and pagination

In many interfaces, we all need to use paging processing, WEB API is no exception, so that can submit data retrieval efficiency, reduce the pressure of server data processing, but also submit the client's data display speed.

The general set interface definition is as follows (universal base class interface).

        <summary>///        Returns a collection of all objects in the database///</summary>//        <returns> collection of specified objects </returns>        [HttpGet] public        virtual list<t> GetAll (string token)        {            //Check whether the user has permission, Otherwise throws Mydenyaccessexception exception            base. Checkauthorized (Authorizekey.listkey, token);            list<t> list = Basebll.getall ();            return list;        }

However, such a return record will be more, in general, paging is required, then the processing interface of the paging is defined as follows.

        <summary>        ////query the database based on criteria and return a collection of objects (for paging data display)///</summary>//        <returns> collection of specified objects </returns>        [HttpPost] public        virtual pagedlist<t> findwithpager (string condition, pagerinfo Pagerinfo, String token)

Paging interface, in the results returned here, using a pagelist generic class, which facilitates us to get the current record and total, it is defined as follows.

    <summary>////page Collection///    </summary>/    <typeparam name= "T" > Objects </typeparam> Public    class Pagedlist<t>    {//<summary>//*        Total number of records returned///        </summary> public        int Total_count {get; set;}        <summary>////List collection///        </summary> public        list<t> list {get; set;}    }

Finally, the entire paging Processing Web API interface implementation is as follows.

        <summary>        ////query the database based on criteria and return a collection of objects (for paging data display)///</summary>//        <returns> collection of specified objects </returns>        [HttpPost] public        virtual pagedlist<t> findwithpager (string condition, pagerinfo Pagerinfo, string token)        {            //Check whether the user has permission or throw mydenyaccessexception exception            base. Checkauthorized (Authorizekey.listkey, token);            list<t> list = Basebll.findwithpager (condition, pagerinfo);            The format that is constructed into JSON is passed            var result = new Pagedlist<t> () {total_count = pagerinfo.recordcount, list = list};            return result;        }

The Web API code for the last client call paging is shown below.

        <summary>        ////query the database based on criteria and return a collection of objects (for paging data display)///</summary>//        <param name= "condition" > Conditions of Inquiry </param>//        <param name= "Pagerinfo" > Pagination entity </param>//        <returns> Specify the collection of objects </returns> public        Virtual list<t> findwithpager (string condition, ref Pagerinfo Pagerinfo)        {            var action = "Findwithpager";            String url = Gettokenurl (action) + string. Format ("&condition={0}", condition);            var postdata = Pagerinfo.tojson ();            list<t> result = new list<t> ();            pagedlist<t> list = Jsonhelper<pagedlist<t>>. Convertjson (URL, postdata);            if (list = null)            {                = list.total_count;//modifies the total number of records                result =  list.list;            }            return result;        

4. Integrated Web API interface for mixed frame interface

Throughout the platform building of the Web API and the integration of the hybrid framework, I have developed and integrated the modules in a relatively independent way, implementing a unified approach from direct access to the database, data acquisition in WCF services, and access to data through WEBAPI invocation. This enables a high degree of integration of the entire hybrid framework.

The core of the whole hybrid framework is to integrate the reusable modules in a relatively independent way, and we can quickly build a unified application platform on a certain basis.

The complete WEBAPI platform, which includes the server content, publishes the corresponding Web API interface in the way of API controller.

Within the standalone module of each hybrid framework, we encapsulate the corresponding Web API client invocation processing, which implements the invocation of the Web API.

Under WIN10, use the Web API mode to run the hybrid framework, and get the main interface effect as shown below.

The standalone module Rights Management System interface is shown below.

The articles in the series are as follows:

Application of WEB API application architecture in WinForm Hybrid Framework (1)

Application of WEB API application architecture in WinForm Hybrid Framework (2)--Processing of custom exception results

Web API Interface Design Experience Summary

Application of WEB API application architecture in WinForm Hybrid Framework (3) process decomposition of--winfrom interface call WEBAPI

Application of WEB API application architecture in WinForm Hybrid Framework (4)--quickly develop a full suite of applications with code generation tools

Application of WEB API application architecture in WinForm Hybrid Framework (5)--how system-level dictionaries coexist with company-level dictionaries

Written by: Wu Huacong http://www.iqidi.com

Web API Interface Design (learning)

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.