. NET WeChat official account to obtain OpenID and user information,. netopenid

Source: Internet
Author: User
Tags openid

. NET public account to obtain OpenID and user information,. netopenid

The examples in this article share with you how to obtain the user's OpenID on the public platform for your reference. The specific content is as follows:

Index. aspx. cs code:

Public partial class Index: System. web. UI. page {// user ID public string openid = ""; // public ID public string appid = ConfigurationManager. appSettings ["AppId"]; public string appsecret = ConfigurationManager. appSettings ["AppSecret"]; public string redirect_uri = HttpUtility. urlEncode (" http://www.bkjia.com "); Public string scope =" [Delete this field and fill in the request type, for example, snsapi_userinfo] "; # The region display page is 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) {/** obtain openid for authentication part: * Temporary authentication code * // authentication part: Step 2 get code string code = Request ["code"]; if (string. isNullOrEmpty (code) {// if the code fails to be obtained, pull OpenAccess () again;} // for authentication: Step 3, obtain 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); // The authentication part. For more information, see 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 into an array // The following information is obtained in Step 4: nickname = outputObj1 ["nickname"]. toString (); // nickname sex = outputObj1 ["sex"]. toString (); // gender or other headimgurl = outputObj1 ["headimgurl"]. toString (); // profile picture url province = outputObj1 ["province"]. toString (); country = outputObj1 ["country"]. toString (); language = outputObj1 ["language"]. toString (); city = outputObj1 ["city"]. toString (); // enter the obtained user information in the session ["openid"] = outputObj1 ["openid"]; // switch back to the portal // OpenAccess ();} /** access entry * Open to the menu and call * @ param $ dir_url source url * @ since 1.0 * @ return void */public void OpenAccess () {// determine that the session does not exist if (Session ["openid"] = null) {// authentication step 1: redirect to the 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 = oau2# wechat_redirect ", appid, redirect_uri); Response. redirect (url) ;}// determine whether the session has an else {// jump to the front-end page. aspx Response. redirect (Request. url. toString ());}}}

Index. aspx content:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="TEST.Index" %><!DOCTYPE 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 a post request /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "url"> url </param> /// <param name = "postData"> post Data </param> /// <returns> </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 ;}/// <summary> // The V3 interface is in Xml format, therefore, this method is available /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "url"> </param >/// <param name = "xmlString"> </param> /// <returns> </returns> public static T PostXmlResponse <T> (string url, string xmlString) where T: class, new () {if (url. 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> /// deserialize Xml /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "xmlString"> </param> // <returns> </returns> public static T XmlDeserialize <T> (string xmlString) where T: class, new () {try {var ser = new XmlSerializer (typeof (T); using (var reader = new StringReader (xmlString) {return (T) ser. deserialize (reader) ;}} catch (Exception ex) {throw new Exception ("XmlDeserialize Exception: xmlString:" + xmlString + "Exception message:" + ex. message );}}}

Result

This article has been compiled into ASP. NET development tutorial summary. You are welcome to learn and read it.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

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.