又重写了一遍,感觉收获挺大,记录一下
项目引用
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Script.Serialization;
1 public class GetMessage: IHttpHandler 2 { 3 string AppID = ""; 4 string Secret = ""; 5 string Url = ""; 6 string Code = ""; 7 HttpContext context = null; 8 //传送 HttpContext 页面传 HttpContext.Current 9 public GetMessage(string Url, string AppID, string State,string Secret,HttpContext context) 10 { 11 ProcessRequest (context); 12 this.AppID = AppID; 13 this.Secret = Secret; 14 string code = context.Request.QueryString["code"]; 15 if (string.IsNullOrEmpty(code)) 16 { 17 this.Url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + AppID + "&redirect_uri=" + Url + "&response_type=code&scope=snsapi_userinfo&state=" + State + "#wechat_redirect"; 18 context.Response.Redirect(this.Url); 19 } 20 else { 21 this.Code = code; 22 } 23 } 24 25 26 27 28 29 30 public void Get() 31 { 32 var client = new System.Net.WebClient(); 33 client.Encoding = System.Text.Encoding.UTF8; 34 35 this.Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + this.AppID + "&secret=" + this.Secret + "&code=" + this.Code + "&grant_type=authorization_code"; 36 37 var data = client.DownloadString(Url); 38 39 JObject jo = (JObject)JsonConvert.DeserializeObject(data.ToString());//这种方式只能单个获取值,如果JSON中不包含的话,还会报错 40 var serializer = new JavaScriptSerializer();//这种方式则会很好的转化为 字典类型,如果JSON中不存在,则相应的值为 NULL 41 try 42 { 43 string access_token = jo["access_token"].ToString(); 44 string openid = jo["openid"].ToString(); 45 46 47 var User = serializer.Deserialize<Dictionary<string, string>>(data); 48 string openid1; 49 if (!User.TryGetValue("openid", out openid1)) 50 { context.Response.Write("取名错误"); }//直接输出到页面上 51 52 53 54 Url = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid); 55 data = client.DownloadString(Url); 56 57 58 59 User = serializer.Deserialize<Dictionary<string, string>>(data); 60 61 var userInfo = serializer.Deserialize<Dictionary<string, object>>(data); 62 foreach (var key in userInfo.Keys) 63 { 64 context.Response.Write(string.Format("{0}: {1}", key, userInfo[key]) + "<br/>"); 65 } 66 } 67 catch { 68 context.Response.Write(data); 69 } 70 } 71 72 73 public void ProcessRequest(HttpContext context) 74 { 75 this.context = context; 76 } 77 public bool IsReusable 78 { 79 get { return true; } 80 } 81 }
摘自 麦舒 https://www.cnblogs.com/ansiboy/