Apply to: This article applies to a certain micro-credit development base of users
Introduction:
after spending 300 of the ocean to apply for a micro-trust public platform, it was found that the micro-letter public number could not be used to login the website (not micro-letter opened) to obtain micro-letter account. After careful study, we found that it would take 300 more oceans to apply for a micro-letter open platform to access the site's login. So as a dick silk programmer I think of myself to do a login interface.
Tools and Environment:
1. VS2013. net4.0 C # MVC4.0 Razor
2. Plugin
A. Microsoft.AspNet.SignalR; always get background data
B.gma.qrcodenet.encoding text Generation two-dimensional code
The goal achieved
1. Open the Web site login page on the computer, prompting the user to confirm using the micro-mail scan login.
2. After the user through the micro-letter scanning confirmation, the computer automatically received confirmation information to jump to the site home page.
Principle Analysis
1.SignalR is a magical tool that sends information from browser A to the server, and the server automatically pushes messages to the specified browser B. So my plan is to use a computer browser to open the login page, generate a two-dimensional code (content with the micro-trust Public Platform Web page users authorized URL), using micro-letter code to open this site. Will obtain the micro-letter user OpenID through SIGNALR to the Computer browser, realizes the login function
Implementation process
1. Micro-Credit registration and permissions from the platform (skip ...)
New MVC Web site in 2.vs2013, I use the environment for. NET4.0 C # MVC4.0 Razor engine (personal habits).
3. Install SIGNALR
VS2013 Click Tool ==> Library Package Manager ==> Package Management Console
Enter the following command:
install-package microsoft.aspnet.signalr-version 1.1.4
. net4.0 MVC4 Environment recommended installation 1.1.4 High version is not installed
Installation SINGNALR Successful
Set SIGNALR
var config = new Microsoft.AspNet.SignalR.HubConfiguration ();
Config. Enablecrossdomain = true;
RouteTable.Routes.MapHubs (config);
Create a new class PushHub.cs
Using Microsoft.AspNet.SignalR;
Using Microsoft.AspNet.SignalR.Hubs;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web; Namespace WD. c.utility {///<summary>///callout Single javascription name to connect///</summary> [Hubname ("Pushhub")] public CLA SS Pushhub:hub {///<summary>///temporary Save requested user///</summary> static dictionary<string, string> Rli
st = new Dictionary<string, string> (); <summary>///login request user; Open Login page executes this method to record the ID///</summary> public void ruserconnected () {if!r List. ContainsKey (Context.connectionid)) rlist. Add (Context.connectionid, String.
Empty); The Client way represents the GetUserID method that sends the browser to the specified ID, and the browser obtains Context.connectionid clients.client from the background via the Javascrip method GetUserID (String) ( Context.connectionid).
GetUserID (Context.connectionid); }///<summary>///the user who actually logged in///</summary>///<param name= "Ruser" > Requested users id</param>/// Ram Name= "Loguserid" > Micro-letter openid</param> public void loguserconnected (string ruser, String loguserid) {if (rlist. ContainsKey (Ruser)) {rlist.
Remove (Ruser);
The client means that the browser sends the GetUserID method to the specified ID, and the browser obtains the login success in the background via the Javascrip method Userloginsuccessful (bool,string), and the micro-letter OpenID
Clients.client (Ruser). Userloginsuccessful (True, Loguserid);
}
}
}
}
Create a new MVC controller "LoginController.cs", which does not look at another tutorial;
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC; Namespace WD.
C.controllers {public class Logincontroller:controller {////Get:/login////<summary>///Login home, computer side Open </summary>///<returns></returns> public ActionResult Index () {/* reference https://mp.weixin.qq.com/w IKI?T=RESOURCE/RES_MAIN&ID=MP1421140842&TOKEN=&LANG=ZH_CN *1.url is used to generate two-dimensional code for micro-letter scanning *2. Format Reference Micro-trust from platform help * https:/ /open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=redirect_uri&response_type=code
&scope=scope&state=state#wechat_redirect If you are prompted "This link cannot be accessed", check that the parameter is filled in incorrectly and that you have the authorization scope permission for the scope parameter. *3.redirect_uri content for the return address, developers need to first go to the public platform in the "Development-interface permissions-Web services-Web accounts-Web licensing access to user Profiles" configuration options, modify the authorization callback domain name *4.redirect_ The URI should be recalled to the Wxlog page and UrlEncode encoded, such as: Redirect_uri=geturlencode ("http://your site/login/wxlog?ruser="); RUSER is configured */Viewbag.url = string for Context.connectionid to view in Pushhub. Format ("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&
STATE={2} #wechat_redirect ", B.helper.appid, Geturlencode (" http://your website/login/wxlog?ruser= "), Guid.NewGuid ());
return View (); ///<summary>///Login Confirmation page, micro-client open///</summary>///<param name= "Ruser" ></param>///<retu Rns></returns> public ActionResult Wxlog (string ruser) {//Use micro-letter Login if (!string.
IsNullOrEmpty (Code)) {string loguser= B.helper.getopenidbycode (code);
session["Loguserid"] =loguser;
Viewbag.loguserid = LogUser;
} viewbag.ruser = Ruser;
return View ();
}
}
}
The
Controller "QRController.cs" is used for text generation of two-dimensional code
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using SYSTEM.WEB.MVC; Namespace WD. C.controllers {public class Qrcontroller:controller {////Get:/qr/public actionresult Index () {return View
(); ///<summary>///get 2 D code picture///</summary>///<param name= "str" ></param>///<returns> </returns> public ActionResult getqrcodeimg (string str) {using (var ms = new System.IO.MemoryStream ()) {Stri
ng stringtest = str;
Getqrcode (Stringtest, MS);
Response.ContentType = "Image/png"; Response.OutputStream.Write (Ms. GetBuffer (), 0, (int) Ms.
Length);
System.Drawing.Bitmap img = new System.Drawing.Bitmap (100, 100); Img.
Save (MS, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End (); Return File (Ms.
ToArray (), @ "Image/jpeg"); } private static bool Getqrcode (string strcontent, System.IO.MemoryStream ms) {Gma.QrCodeNet.Encoding.ErrorCorrect Ionlevel ECL = Gma.QrCodeNet.Encoding.ErrorCorrectiONLEVEL.M; Error correction Horizontal string content = strcontent;//to be encoded content Gma.QrCodeNet.Encoding.Windows.Render.QuietZoneModules Quietzones = gma.q RCodeNet.Encoding.Windows.Render.QuietZoneModules.Two;
blank area int modulesize = 12;//size var encoder = new Gma.QrCodeNet.Encoding.QrEncoder (ECL);
Gma.QrCodeNet.Encoding.QrCode QR; if (encoder. Tryencode (content, out QR))//encode the contents and save the generated matrix {var render = new Gma.QrCodeNet.Encoding.Windows.Render.GraphicsRenderer (New
Gma.QrCodeNet.Encoding.Windows.Render.FixedModuleSize (Modulesize, quietzones)); Render. WriteToStream (QR.
Matrix, System.Drawing.Imaging.ImageFormat.Png, MS);
else {return false;
return true;
}
}
}
View open SIGNALR
var chat = $.connection.pushhub;
$.connection.hub.start (). Done (function () {
Chat.server.ruserConnected ();
});
$.connection.pushhub Correspondence
Chat.server.ruserConnected ();
Indicates that the Runserconnected method is invoked after the call to "Pushhub" to increase the current browser's ConnectionID in the temporary table
Chat.client.getUserId = function (Ruserid)
{
//two D-code generated text
$ ("#loga"). attr ("src", "@ViewBag. Url" + Ruserid) ;
}
Indicates post-station data
Return to the viewer after receiving data
chat.client.userLoginSuccessful = function (r, userid) {
if (r) {
$.post ("/login/addsession/", {Userid:userid} , function (R2) {
if (R2) {
location.href = "/home/";}}
)
}
;
User login via micro-letter
Receive micro-letter OpenID
$.post ("/login/addsession/", {Userid:userid}, function (R2) {
if (R2) {
Location.href = "/home/";
}
})
Perform post to background to increase login information, and then go to/home/home page after successful
<summary>
///Save micro-Letter Confirmation login to return the OpenID, as the site of the session["Loguserid"]
///</summary>
///< param name= "userid" ></param>
///<returns></returns> public
jsonresult addsession ( string userid)
{
session["loguserid"] = userid;
Return Json (TRUE);
}
Login/wxlog.cshtml This page opens on a micro-letter
@{viewbag.title = "Wxlog";} <script src= "~/scripts/jquery.signalr-1.1.4.min.js" ></script> <script src = "~/signalr/hubs" ></script> <script> $ (function () {//connection signalr pushhab var chat = $.connection.pushhub
;
Start $.connection.hub.start (). done (); $ ("#btnLog"). Click (function () {//login, send message to Server chat.server.logUserConnected ("@ViewBag. Ruser", "@ViewBag. Loguserid")
;
});
});
</script>
Getopenidbycode (Code) method
Reference Https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN
For users who have been concerned about the public number, if the user from the public number of sessions or custom menu access to the public number of the page authorization page, even if the scope for Snsapi_userinfo, is also a silent authorization, users do not perceive.
Specifically, the page authorization process is divided into four steps:
1, guide the user to enter the authorization page consent authorization, get code
2, through the code in Exchange for Web page authorization Access_token (and basic support Access_token different)
3, if necessary, developers can refresh the page authorization Access_token, to avoid expiration
4, through the website authorized Access_token and OpenID to obtain user basic information (support Unionid mechanism)
public static string Getopenidbycode (string code)
{
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);
using (System.Net.WebClient client = new System.Net.WebClient ())
{
string tempstr= client. downloadstring (URL);
var regex= new Regex (@ "\" "openid\" ": \" "[^\" "]+?\" ",", regexoptions.ignorecase);
String tempstr2= regex. Match (TEMPSTR). Value;
Return TEMPSTR2. Substring (TEMPSTR2. Length-12);
}
Wonderful topic sharing: ASP.net micro-credit Development tutorial Summary, Welcome to learn.
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.