. NET Micro public number access to OpenID and user information _ Practical Tips

Source: Internet
Author: User
Tags convert json to array openid

The example of this article for everyone to share the micro-trust public platform to achieve access to the user OpenID method for your reference, the specific contents are as follows

Index.aspx.cs Code:

 Public partial class Index:System.Web.UI.Page {//user ID public string OpenID = "";
  The public number information section is publicly string AppID = configurationmanager.appsettings["AppID"];
  public string Appsecret = configurationmanager.appsettings["Appsecret"];
  public string Redirect_uri =httputility.urlencode ("http://www.jb51.net");

  public string scope = "" Delete this and fill in the request type, for example: Snsapi_userinfo "";
  #region Display page public string Accesstoken;
  public string Nickname;
  public string sex;
  public string Headimgurl;
  public string Province;
  public string Country;
  public string language;

  public, String city;
  public string privilege = ""; #endregion protected void Page_Load (object sender, EventArgs e) {/* micro-authentication access to the OpenID section: * Temporary authentication code *//
   Micro-Credit Certification section: The second step to obtain code string code = request["Code"]; if (string.
   IsNullOrEmpty (code) {//If the code is not successful, pull again openaccess (); //micro-Credit Certification section: Step three get OpenID string url = string. Format ("https://api.weixin.qq.com/sns/oauth2/access_tOken?appid={0}&secret={1}&code={2}&grant_type=authorization_code ", AppID, Appsecret, code);
   string result = Httpclienthelper.getresponse (URL);
   Loghelper.writefile (result);

   Jobject outputobj = jobject.parse (result); Micro-Credit Certification section: Fourth step to get more information Accesstoken = outputobj["Access_token"].
   ToString (); OpenID = outputobj["OpenID"].
   ToString (); url = string. Format ("Https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_cn", Accesstoken,
   OpenID);
   String result1 = Httpclienthelper.getresponse (URL);
   Loghelper.writefile (RESULT1); Jobject outputObj1 = Jobject.parse (RESULT1);//convert JSON to array//The following is the information obtained from step fourth: Nickname = outputobj1["nickname"]. ToString (); Nickname sex = outputobj1["Sex"]. ToString (); Gender of what Headimgurl = outputobj1["Headimgurl"]. ToString (); Avatar url province = outputobj1["province"].
    ToString ();; Country = outputobj1["Country"].
    ToString ();; Language = outputobj1["language"].
    ToString ();; City = outputobj1["City "].
   ToString ();;
   The user information obtained is filled into the session session["OpenID"] = outputobj1["OpenID"];
  Turning back to the entrance//openaccess (); * * * Access entry * open to micro-letter menu Call * @param $dir _url Source URL * @since 1.0 * @return void/public void OPENACC ESS () {//Judge session does not exist if (session["OpenID"] = = NULL) {//Authentication first step: Redirect Jump to authentication url string url = string. Format ("Https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&&response_
    Type=code&scope=snsapi_userinfo&m=oauth2#wechat_redirect ", AppID, Redirect_uri);
   Response.Redirect (URL);
   //Judge session exists else {//Jump to front page. aspx Response.Redirect (Request.Url.ToString ());
 }
  }

 }

Index.aspx content:

<%@ Page language= "C #" autoeventwireup= true "codebehind=" Index.aspx.cs "inherits=" TEST. Index "%> <! DOCTYPE html> <html xmlns= "http://www.w3.org/1999/xhtml" > <head runat= "Server" > <title></ title> <meta name= "viewport" content= "width=device-width, initial-scale=1"/> <style "type=" text/css "> t
  d {Word-wrap:break-word;  } </style> <script type= "Text/javascript" > </script> </head> <body> <form id= "Form1" runat= "Server" > <div id= "WU" runat= "Server" > <table style= "width:100%;" > <tr> <td style= "width:150px;" > <p> openid:<%=openid%></p> </td> <td> <p> Nickname: <%=nickname%></p> </td> <td> <p> sex:<%=sex%></p> </td > </tr> <tr> <td> <p> language:<%=language%></p> </td> <td> <p> city:<%=city%></p> </td> <td> <p&gt
      ; country:<%=country%></p> </td> </tr> <tr> <td> <p> Head Imgurl:<img width= "50px;" src= "<%=headimgurl%>" alt= "" ></p> </td> <td> <P&G
      T privilege:<%=privilege%></p> </td> <td> </td> </tr> </table> &

 lt;/div> </form> </body> </html>

HttpClientHelper.cs Code:

public class Httpclienthelper {///<summary>///GET request///</summary>///<param name= "url" > </param>///<returns></returns> public static string GetResponse (string url) {if (URL).
   StartsWith ("https")) {servicepointmanager.securityprotocol = Securityprotocoltype.tls;
   var httpclient = new HttpClient ();

   HTTPCLIENT.DEFAULTREQUESTHEADERS.ACCEPT.ADD (New Mediatypewithqualityheadervalue ("Application/json")); Httpresponsemessage response = Httpclient.getasync (URL).

   result; if (response. Issuccessstatuscode) {string result = response. Content.readasstringasync ().
    result;
   return result;
  return null; public static T getresponse<t> (string url) where T:class, new () {if (URL).

   StartsWith ("https")) Servicepointmanager.securityprotocol = Securityprotocoltype.tls;
   var httpclient = new HttpClient (); HTTPCLIENT.DEFAULTREQUESTHEADERS.ACCEPT.ADD (New mediatypewithqualityHeadervalue ("Application/json")); Httpresponsemessage response = Httpclient.getasync (URL).

   result;

   T result = default (t); if (response. Issuccessstatuscode) {task<string> T = response.
    Content.readasstringasync ();

    string s = T.result;
   result = Jsonconvert.deserializeobject<t> (s);
  return result;  ///<summary>///POST request///</summary>///<param name= "url" ></param>///<param  Name= "PostData" >post data </param>///<returns></returns> public static string Postresponse (string URL, string postdata) {if (URL).

   StartsWith ("https")) Servicepointmanager.securityprotocol = Securityprotocoltype.tls;
   Httpcontent httpcontent = new Stringcontent (postdata);
   HttpContent.Headers.ContentType = new Mediatypeheadervalue ("Application/json");

   var httpclient = new HttpClient (); Httpresponsemessage response = Httpclient.postasync (URL, httpcontent).

   result; if (response. IssucceSsstatuscode) {string result = response. Content.readasstringasync ().
    result;
   return result;
  return null; ///<summary>///initiate POST request///</summary>///<typeparam name= "T" ></typeparam>///& Lt;param name= "url" >url</param>///<param name= "postdata" >post data </param>///<returns>& lt;/returns> public static T postresponse<t> (string url, string postdata) where T:class, new () {if ( Url.

   StartsWith ("https")) Servicepointmanager.securityprotocol = Securityprotocoltype.tls;
   Httpcontent httpcontent = new Stringcontent (postdata);
   HttpContent.Headers.ContentType = new Mediatypeheadervalue ("Application/json");

   var httpclient = new HttpClient ();

   T result = default (t); Httpresponsemessage response = Httpclient.postasync (URL, httpcontent).

   result; if (response. Issuccessstatuscode) {task<string> T = response.
    Content.readasstringasync (); string s = T.resUlt
   result = Jsonconvert.deserializeobject<t> (s);
  return result; The///<summary>///V3 interfaces are all XML, so this method///</summary>///<typeparam name= "T" ></TYPEPARAM&G
  T <param name= "url" ></param>///<param name= "xmlstring" ></param>///<returns></r eturns> public static T postxmlresponse<t> (string url, string xmlstring) where T:class, new () {if (U Rl.

   StartsWith ("https")) Servicepointmanager.securityprotocol = Securityprotocoltype.tls;
   Httpcontent httpcontent = new Stringcontent (xmlstring);
   HttpContent.Headers.ContentType = new Mediatypeheadervalue ("Application/json");

   var httpclient = new HttpClient ();

   T result = default (t); Httpresponsemessage response = Httpclient.postasync (URL, httpcontent).

   result; if (response. Issuccessstatuscode) {task<string> T = response.
    Content.readasstringasync ();

    string s = T.result; result = XmldeserializE<t> (s);
  return result; ///<summary>///deserialization xml///</summary>///<typeparam name= "T" ></typeparam>///&L T;param name= "xmlstring" ></param>///<returns></returns> public static T Xmldeserialize<t&gt
    ;(string xmlstring) where T:class, new () {try {var ser = new XmlSerializer (typeof (T)); using (var reader = new StringReader (xmlstring)) {return (T) ser.
    Deserialize (reader); Exception Ex {throw new Exception ("Xmldeserialize exception: xmlstring: + xmlstring +" Exception information: "+ ex.")
   message);

 }
  }
 }

The result is as shown in figure:

This article has been sorted out to the ASP. NET micro-Credit Development tutorial Summary, you are welcome to learn to read.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.