MVC web page authorization to obtain the user's OpenId, mvc to obtain the openid
I recently developed a public platform and made a record. I have also developed it before. I forgot about this development. After half a day, I 'd better take a note.
Note that the framework is used to develop a public platform for MVC. The scenario is to obtain the user's openid on the template page. To verify the page, you can integrate the template page.
Add the following code to _ Layout. cshtml:
Add the GetOpenID method to the AdminUtil class.
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
[H]
var code = HttpContext.Current.Request["code"];
Log.logmsg(code);
string urlpath = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
ViewBag.at = AdminUtil.GetOpenID(urlpath, code);
}
</head>
Add getopenid method to adminutil class
#Region get openid
/// <summary>
///Get openid
/// </summary>
public static string GetOpenID(string redirect_url, string code)
{
string AppID = WXModel.AppID;
string AppSecret = WXModel.AppSecret;
string openid = "";
openid = WXApi.GetOpenID(AppID, redirect_url, code, AppSecret);
return openid;
}
#endregion
Add getopenid method to class wxapi
#Region get openid
/// <summary>
///Get openid
/// </summary>
public static string GetOpenID(string appid, string redirect_url, string code, string screct)
{
string strJson = "";
if (string.IsNullOrEmpty(code))
{
redirect_url = HttpUtility.UrlEncode(redirect_url);
HttpContext.Current.Response.Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&state={2}#wechat_redirect",
appid, redirect_url, new Random().Next(1000, 200000).ToString()));
}
Else
{
strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code",
appid, screct, code));
}
return Tools.GetJsonValue(strJson, "openid");
}
#endregion
public static class WXModel
{
public static string access_token;
public static string AppID;
public static string AppSecret;
}
/// <summary>
///Tools
/// </summary>
public class Tools
{
#Region gets the value of a node in the JSON string
/// <summary>
///Get the value of a node in JSON string
/// </summary>
public static string GetJsonValue(string jsonStr, string key)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(jsonStr))
{
key = "\"" + key.Trim('"') + "\"";
int index = jsonStr.IndexOf(key) + key.Length + 1;
if (index > key.Length + 1)
{
//Truncate the comma first, and if it is the last, truncate the "," sign, and take the minimum value
int end = jsonStr.IndexOf(',', index);
if (end == -1)
{
end = jsonStr.IndexOf('}', index);
}
result = jsonStr.Substring(index, end - index);
Result = result.trim (New char [] {',', '\'}); / / filter quotes or spaces
}
}
return result;
}
#endregion
}
public class HttpRequestUtil
{
#Region request URL, do not send data
/// <summary>
///Request URL, do not send data
/// </summary>
public static string RequestUrl(string url)
{
return RequestUrl(url, "POST");
}
#endregion
#Region request URL, do not send data
/// <summary>
///Request URL, do not send data
/// </summary>
public static string RequestUrl(string url, string method)
{
//Set parameters
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = method;
request.ContentType = "text/html";
request.Headers.Add("charset", "utf-8");
//Send request and get corresponding response data
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//It is not until the request.getresponse() program that the post request is sent to the target web page
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream, Encoding.Default);
//Return result page (HTML) code
string content = sr.ReadToEnd();
return content;
}
#endregion
}
Note: the authorization callback domain needs to be set in the public platform
The above is the whole content of this article. I hope it will help you in your study, and I also hope you can support the help home.