ASP. NET API (MVC) unified management of receiving and returning data from the App interface (JSON format)

Source: Internet
Author: User

Speak not much, directly into the subject.

Requirements: Receive JSON-formatted data based on HTTP requests, returning JSON-formatted data.

Collation: The received data and return data in a unified packaging, convenient processing of receiving and returning data, and validation of the data, through the characteristics of C # to verify token, and the time stamp of the way to uniformly handle the time format of receiving and returning.

Request JSON format:

{    "CMD": "Login",    "Token": "",    "PageNo": 0,    "Onepagenum": 0 ,    " Params ": {        " UserName ":" Emrys ",        " Pwd ":" 123456 "    }}

Return JSON format

{    "CMD": "Login",    "Result": 0,    "resultnote": "Success",    " Totalrecordnum ": 0,    " Pages ": 0,    " PageNo ": 0,    " Detail ": {         "UserName": "Lining",        "email": "[email protected]",        "age": "" "    }}

About the code will be free open source, so do not elaborate, the following are mainly simple applications.

First, create new interface

The direct new class name is consistent with the requested interface cmd name, inherits Baseapiservice, and adds Apiservice after the name, finally implementing the abstract method process

1   Public Overrideapiresult Process ()2         {3             //1. Get Parameters4             //1.1. All parameters are in request, request can get all the received data after encapsulation5             stringcmd =Reqeust.cmd;6             intPageNo =Reqeust.pageno;7             ObjectParamses =Reqeust.params;8 9             //1.2. All the data in the params can be obtained from the params.Ten             stringUserName = convert.tostring (params["UserName"]); One  A             //1.3. Data can be obtained by means of methods -             stringUserName2 = getparams<string> ("UserName"); -             stringPWD = getparams<string> ("PWD"); the             intAge = getparams<int> (" Age"); -  -             //1.4, through the second parameter of Getparams, you can set whether the parameter is a parameter that must be passed in, default to the parameter that must be passed in -             stringUserName3 = getparams<string> ("UserName",false);//username not required parameters to be passed in +             stringUserName4 = getparams<string> ("UserName",true);//username is a parameter that must be passed in -  +             //1.5, the time format has been unified processing the incoming format to a long type of timestamp such as: 1466871403000 ADateTime time = getparams<datetime> (" Time"); at  -             //1.6, such as the parameters passed a lot, through the method getparams a fetch is more troublesome, so if you encounter more parameters, you need to create a new class, the property and params parameters consistent, such as Loginrequestmodel, By means of Converttomodel, the parameters can be encapsulated in the class, which is convenient for using parameters.  -Loginrequestmodel login = converttomodel<loginrequestmodel>(); -  -             //1.7. You can mark an attribute [apirequired] on the property of the passed-in parameter class and the class to mark whether the parameter is a required parameter.  -  in             //2. Set the return value -             //2.1, directly set the return value to             //return Apijson (New {name = "Emrys"}); +  -             //2.2. Return string the             //return Apicontext ("xxxxxxxxxxxxxx"); *  $             //2.3. Return ObjectPanax Notoginseng             //return Apijson (new Loginrequestmodel {}); -  the             //2.4 Directly returns the desired object value +             //return new Apiresultjson {resultnote = "xxxxxxx"}; A               the  +             returnApijson (New{name ="Emrys" }); -}

Second, set permissions to verify each request

If you need to authenticate each request for login, you only need to continue with the validation section in the Main class for 60 rows, and if the request does not require validation, add the attribute Apinotneedtokento the class.

if(NT = =NULL|| (!NT. Notneedtoken)) {//If you need to verify//get user information based on token                    varuser =GetUser (Req.token); if(User = =NULL)                    {                        //determine if token is invalid                        Throw NewApiexception ( $,"token is invalid. "); } req. Apiworkcontext=NewApiworkcontext (); Req. Apiworkcontext.userid=Convert.ToInt32 (user.user_id); Req. Apiworkcontext.useremail=User.email; }

The userid,useremail can then be obtained in the process method in each interface class.

1   // 3 Getting login information 2             int userId = Workcontext.userid;      

Three, the realization of different time formats

If you need to implement different time formats, such as without timestamps, the custom format is: Yyyy-mm-dd HH:mm:ss, inheriting class Datetimeconverterbase, and implementing Readjson and Writejson two methods. and set the time format when you return.

1. Change the code in 100 lines in the code Main

// set the time  format                var New jsonserializersettings {nullvaluehandling = Nullvaluehandling.ignore};                 // set filter null value to not display                JSONSETTINGS.CONVERTERS.ADD (new  unixdatetimeconverter ());  Unixdatetimeconverter is the custom time type.                 return Jsonconvert.serializeobject (res, jsonsettings);

Source Address: Https://github.com/Emrys5/Emrys.API

ASP. NET API (MVC) unified management of receiving and returning data from the App interface (JSON format)

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.