1. First, the client invokes an instance of the interface
1.1 Define the Receive interface result class first
Public class resultmsg { publicboolgetset;} Public string Get Set ; } Public string Get Set ; } }
1.2 User Login As an example, the login request interface input parameters user name password to determine whether the correct
Public StaticResultmsg Checklogin (stringAccountstringpwd) { //Tools.Common1.WriteLog ("Checklogin", "Checklogin", "Account:" + account + "----pwd:" + pwd);Webapiresult msg = WEBAPIHELPER.GETWEBAPI (New{UserName = account, PassWord = pwd},"/useraccounts/login/"); if(Msg. Success) {returnMsg.result; } Else { return NewResultmsg () {title =false, message ="the request interface failed,"+Msg.result.message}; } }
Call the interface, add the access account password in the header to improve the security of the interface
Private Const stringPWD ="abc_2015?"; Private Const stringAccount ="Webaccount"; #regionRequest Webapi/// <summary> ///Request Webapi/// </summary> /// <param name= "model" ></param> /// <param name= "page" ></param> /// <returns></returns> Public StaticWebapiresult Getwebapi (ObjectModelstringpath) {WebClient WC=NewWebClient (); Wc. Headers.add (Httprequestheader.accept,"Application/json"); Wc. Headers.add (Httprequestheader.contenttype,"Application/json; Charset=utf-8"); stringAuth =authorizationhelper.getauthorization1 (account, path, PWD); Wc. Headers.add (Httprequestheader.authorization,auth); byte[] PostData = System.Text.Encoding.UTF8.GetBytes (NewJavaScriptSerializer (). Serialize (model)); Try { byte[] Text = WC. Uploaddata (domain + path,"Post", PostData); stringstr =System.Text.Encoding.UTF8.GetString (Text); return NewJavaScriptSerializer (). Deserialize<webapiresult>(str); } Catch(Exception ex) {return NewWebapiresult () {Success =false, result =NewResultmsg () {title =false, message =Ex. Message}}; } } #endregion }
1.3 Interfaces in another project, the example is as follows:
Under the App_start folder of the interface project, create a new class Loginattribute to determine if the account password transferred in the header is correct
//indicates that the attribute can be used for classes, methods, and attributes cannot be repeatedly placed in front of the same program entity multiple times[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, AllowMultiple =false)] Public classLoginattribute:actionfilterattribute {/// <summary> ///before action is executed/// </summary> /// <param name= "Filtercontext" ></param> Public Override voidonactionexecuting (ActionExecutingContext filtercontext) {//The filter context is empty and throws an exception if(Filtercontext = =NULL) { Throw NewArgumentException ("Filtercontext"); } //get access Path, account number, timestamp, redaction varPath =filterContext.HttpContext.Request.Path.ToString (); varauthorization = filtercontext.httpcontext.request.headers["Authorization"]; if(!string. IsNullOrEmpty (Authorization)) {//Split validation string, Account,mac,salt string[] STRs = authorization. Split (','); if(STRs. Length = =3) { stringaccount = strs[0]. Replace ("account=",""); varMac = strs[1]. Replace ("mac=",""); varSalt = strs[2]. Replace ("salt=",""); if(!string. IsNullOrEmpty (account)) {Try { varPWD =System.configuration.configurationmanager.appsettings[account]. ToString (); stringciphertext =uri.escapedatastring (PISCenter.Common.Utility.GetCiphertext (account, path, salt, pwd)); if(ciphertext. Equals (Mac)) {Base. OnActionExecuting (Filtercontext); } } Catch{Filtercontext.result=NewJsonresult {Data =New{title =false, message ="authentication error, Access denied"}, Jsonrequestbehavior =Jsonrequestbehavior.allowget}; } } Else{Filtercontext.result=NewJsonresult {Data =New{title =false, message ="authentication error, Access denied"}, Jsonrequestbehavior =Jsonrequestbehavior.allowget}; } } Else{Filtercontext.result=NewJsonresult {Data =New{title =false, message ="authentication error, Access denied"}, Jsonrequestbehavior =Jsonrequestbehavior.allowget}; } } Else{Filtercontext.result=NewJsonresult {Data =New{title =false, message ="authentication error, Access denied"}, Jsonrequestbehavior =Jsonrequestbehavior.allowget}; } } }
1.4 Method Body of the landing
[HttpPost] PublicJsonresult Login (checklogininput model) {if(model = =NULL||string. IsNullOrEmpty (model. PassWord) | | (string. IsNullOrEmpty (model. UserName) &&string. IsNullOrEmpty (model. Mobilephone )) {returnFail ("The submission parameter is incorrect"); } Checkloginoutput UA=_useraccountsappservice.checklogin (model); if(ua!=NULL&&ua. Id>0) { returnSuccess (Newtonsoft.Json.JsonConvert.SerializeObject (UA)); } Else { returnFail ("Login failed, account or password error"); } }
The whole process is over.
Attached: in the project
Public Static stringGetAuthorization1 (stringAccountstringPathstringpassword) {StringBuilder SB=NewStringBuilder (); stringDate=uri.escapedatastring (Gettimestamp ()); Sb. AppendFormat ("account={0},mac={1},salt={2}", Uri.escapedatastring, uri.escapedatastring (getciphertext (account, Path, Date,password), date); returnsb. ToString (); }
In the interface project:
/// <summary> ///SHA-1 Encryption of the visitor, returning encrypted ciphertext/// </summary> /// <param name= "Account" >Account Number</param> /// <param name= "path" >access Path/start,/End</param> /// <param name= "Date" >time Stamp</param> /// <param name= "password" >Password</param> /// <returns></returns> Public Static stringGetciphertext (stringAccountstringPathstringDatestringpassword) { stringCiphertext = account +"\ n"+ Date +"\ n"+ path. ToLower () +"\ n"+ Password +"\ n"; System.Security.Cryptography.HMACSHA1 HMACSHA1=NewSystem.Security.Cryptography.HMACSHA1 (); Hmacsha1. Key=Encoding.UTF8.GetBytes (password); byte[] DataBuffer =Encoding.UTF8.GetBytes (ciphertext); byte[] Hashbytes =Hmacsha1.computehash (DataBuffer); Ciphertext=convert.tobase64string (hashbytes); returnciphertext; }
The C # calling interface receives the result "get,post generic"