Android request Asp.net web API by cooki

Source: Internet
Author: User

Today, I will explain how Android uses cooki to access the web API that requires authentication.

Add the following identity verification controler to the web API project:

 Public   Class  Logoncontroller: apicontroller {  Public   Bool  Post ([frombody] user model ){  Using ( VaR DB = New  Heredbcontext ()){  VaR Query = dB. allusers. Where (p) => P. Name = model. Name & P. Password =Model. Password );  If (Query. Count ()> 0  ){
// Save the client verification in cooki formsauthentication. setauthcookie (model. Name, False ); Return True ;}} Return False ;}}

 

There is another API controler that requires authentication in the web API, as shown below:

 [Authorize]  Public   Class  Userscontroller: apicontroller {  Public Ienumerable <user> Getallusers () {log. I (  "  Getallusers () is called.  "  );  Using ( VaR DB = New Heredbcontext ()){  Return  DB. allusers. tolist ();}}  Public User getuserbyid ( Int  ID ){  Using ( VaR DB = New  Heredbcontext ()){  VaR User = dB. allusers. firstordefault (p) => P. ID = ID ); If (User = Null  ){  Throw   New  Httpresponseexception (httpstatuscode. notfound );}  Return  User ;}}  Public User getusersbyuid ( String  UID ){  Using ( VaR DB =New  Heredbcontext ()){  Foreach ( VaR User In  DB. allusers ){  If (User. uid = UID ){  Return  User ;}}}  Throw   New Httpresponseexception (httpstatuscode. notfound );}  Public  Httpresponsemessage adduser ([frombody] user ){  If (User = Null  ){  Return Request. createresponse < String > (Httpstatuscode. Forbidden, "  User is null!  "  );} Using ( VaR DB = New  Heredbcontext ()){  If (Db. allusers. Where (p) => String . Equals (P. Name, user. Name). Count ()> 0  ){  Return Request. createresponse < String > (Httpstatuscode. Conflict, user. Name + "  Already existed! "  );} DB. allusers. Add (User); DB. savechanges ();  Return Request. createresponse < String > (Httpstatuscode. Accepted, user. UID );}}} 

If you want to access this web API through the android client, you need to authenticate the web API. You can write the client as follows:

 Import  Java. Io. bufferedreader;  Import  Java. Io. ioexception;  Import  Java. Io. inputstreamreader; Import  Java. util. List;  Import  Org. Apache. http. httpentity;  Import  Org. Apache. http. httpresponse;  Import  Org. Apache. http. namevaluepair;  Import  Org. Apache. http. Client. clientprotocolexception;  Import  Org. Apache. http. Client. cookiestore;  Import  Org. Apache. http. Client. entity. urlencodedformentity; Import  Org. Apache. http. Client. Methods. httpget;  Import  Org. Apache. http. Client. Methods. httppost;  Import  Org. Apache. http. Client. Methods. httpurirequest;  Import  Org. Apache. http. impl. Client. abstracthttpclient;  Import  Org. Apache. http. impl. Client. defaulthttpclient;  Import  Android. util. log;  Public  Abstract   Class  Httphelper {  Private   Final   Static String tag = "httphelper" ;  Private   Final   Static String api_url = "http://your.url/api" ;  Private   Static  Cookiestore scookiestore;  Public  Static String invokepost (string action, list <namevaluepair> Params ){  Try  {String URL = Api_url + Action + "/" ; Log. D (tag, "Url is" + URL); httppost = New  Httppost (URL );  If (Params! = Null & Params. Size ()> 0 ) {Httpentity entity =New Urlencodedformentity (Params, "UTF-8" ); Httppost. setentity (entity );}  Return  Invoke (httppost );}  Catch  (Exception e) {log. E (TAG, E. tostring ());}  Return   Null  ;}  Public   Static  String invokepost (string action ){  Return Invokepost (action, Null  );}  Public   Static String invokeget (string action, list <namevaluepair> Params ){  Try  {Stringbuilder sb = New  Stringbuilder (api_url); sb. append (action );  If (Params! = Null  ){  For (Namevaluepair Param: Params) {sb. append ( "? " ); Sb. append (Param. getname (); sb. append ( "=" ); Sb. append (Param. getvalue () ;}} log. D (tag, "Url is" + SB. tostring (); httpget = New  Httpget (sb. tostring ());  Return  Invoke (httpget );}  Catch (Exception e) {log. E (TAG, E. tostring ());}  Return   Null  ;}  Public   Static  String invokeget (string action ){  Return Invokeget (action, Null  );}  Private   Static  String invoke (httpurirequest request)  Throws Clientprotocolexception, ioexception {string result = Null  ; Defaulthttpclient httpclient = New  Defaulthttpclient ();  //  Restore cookie          If (Scookiestore! = Null  ) {Httpclient. setcookiestore (scookiestore);} httpresponse response = Httpclient.exe cute (request); stringbuilder Builder =New  Stringbuilder (); bufferedreader Reader = New Bufferedreader ( New  Inputstreamreader (response. getentity (). getcontent ()));  For (String S = reader. Readline (); s! = Null ; S = Reader. Readline () {builder. append (s);} result = Builder. tostring (); log. D (tag, "Result is (" + Result + ")" ); //  Store Cookie Scookiestore = (Abstracthttpclient) httpclient). getcookiestore ();  Return  Result ;}} 

During debugging, you must host the web API to IIS and enable form authentication for IIS.

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.