微信小程序用户登录服务器端asp,C#获取微信小程序openid等用户信息(前端+asp.net服务器端代码)...

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.Services;usingSystem.Web.Script.Serialization;usingSystem.Web.Script.Services;usingSystem.Runtime.Serialization.Json;usingSystem.Data;usingSystem.Text;usingSystem.IO;usingSystem.Net;usingNewtonsoft.Json;usingNewtonsoft.Json.Linq;///

///api 的摘要说明///

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)]//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。

[System.Web.Script.Services.ScriptService]public classapi : System.Web.Services.WebService

{

[WebMethod]public void OpenID(stringcode)

{//临时登录凭证code 获取 session_key 和 openid

string js_code =code;//此处填写自己小程序的appid和secret

string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=" + js_code + "&grant_type=authorization_code";

HttpWebRequest request=(HttpWebRequest)WebRequest.Create(serviceAddress);

request.Method= "GET";

request.ContentType= "textml;charset=UTF-8";

HttpWebResponse response=(HttpWebResponse)request.GetResponse();

Stream myResponseStream=response.GetResponseStream();

StreamReader myStreamReader= newStreamReader(myResponseStream, Encoding.UTF8);string jsonData =myStreamReader.ReadToEnd();

myStreamReader.Close();

myResponseStream.Close();string jsonString =jsonData;

JObject json=JObject.Parse(jsonString);string openid = json["openid"].ToString();

Context.Response.Write(GetJson(openid));

}#region 把对象序列化 JSON 字符串

///

///把对象序列化 JSON 字符串///

/// 对象类型

/// 对象实体

/// JSON字符串

public static string GetJson(T obj)

{//记住 添加引用 System.ServiceModel.Web

/**

* 如果不添加上面的引用,System.Runtime.Serialization.Json; Json是出不来的哦

**/DataContractJsonSerializer json= new DataContractJsonSerializer(typeof(T));using (MemoryStream ms = newMemoryStream())

{

json.WriteObject(ms, obj);string szJson =Encoding.UTF8.GetString(ms.ToArray());returnszJson;

}

}#endregion}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值