Maison >Applet WeChat >Développement WeChat >La page Web de développement du compte public WeChat autorise l'obtention d'informations de base sur les utilisateurs
Si l'utilisateur accède à une page Web tierce dans le client WeChat, le compte officiel peut obtenir les informations de base de l'utilisateur via le mécanisme d'autorisation de la page Web WeChat, puis mettre en œuvre une logique métier.
Remarque : Il existe deux manières d'autoriser les pages Web
Pour plus d'autorisation Web, veuillez vous référer à la documentation officielle du site Web : Autorisation Web
L'autorisation silencieuse peut obtenir les informations de base de l'utilisateur lorsque l'utilisateur paie Attention, l'utilisateur n'a pas besoin d'effectuer ce processus de perception.
La première étape consiste à transmettre la demande via la classe d'usine
/// <returns></returns> public string HandleRequest() { string response = string.Empty; EventMessage em = EventMessage.LoadFromXml(RequestXml); if (em != null) { switch (em.Event.ToLower()) { case ("subscribe"): response = SubscribeEventHandler(em);//通过工厂类分发过来的请求,匹配到关注事件 break; case ("unsubscribe"): response = Un_SubscribeEventHandler(em); break; case "click": response = ClickEventHandler(em); break; } } return response; }
La deuxième étape consiste à écrire des événements axés sur l'utilisateur
WeChat.Messages.TextMessage tm = = em.FromUserName; tm.FromUserName = em.ToUserName; tm.CreateTime ==
<span style="color: #000000;"> </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> tm.GenerateContent();<br> }</span>
La troisième étape consiste à obtenir les informations de base de l'utilisateur en fonction de l'OpenId obtenu et accesstoken (ici La démonstration consiste à stocker l'utilisateur dans la base de données)
/// <summary> /// 根据OpenId将此条粉丝记录插入数据库中 /// </summary> /// <param name="FromUserName"></param> /// <param name="ToUserName"></param> public void ShowUserInfo(string FromUserName, string ToUserName) { try { Models.Users user = new Models.Users(); DAL.User userInfo = new DAL.User(); //获取accesstoken,获取用户基本信息需要Openid和accesstoken即可 accesstoken = Utility.Context.AccessToken; string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN", accesstoken, FromUserName); string result = HttpUtility.GetData(url); XDocument doc = XmlUtility.ParseJson(result, "root"); XElement root = doc.Root; if (root != null) { #region 取值/存值 subscribe = root.Element("subscribe").Value;//是否关注 1 是关注 nickname = root.Element("nickname").Value; //昵称 sex = root.Element("sex").Value; //性别什么 headimgurl = root.Element("headimgurl").Value; //头像url province = root.Element("province").Value;//地区 country = root.Element("country").Value; language = root.Element("language").Value; subscribe_time = root.Element("subscribe_time").Value; DateTime create_time = Common.GetTime(subscribe_time);//将时间戳转换为当前时间 city = root.Element("city").Value; user.OpenID = FromUserName;//OpenID即粉丝ID user.PublicId = ToUserName; user.UserID = FromUserName; user.NickName = nickname; user.Sex = int.Parse(sex); user.Subscribe = int.Parse(subscribe); user.Country = country; user.Province = province; user.City = city; user.CreateDate = create_time; user.HeadimgUrl = headimgurl; //将user实体存入数据库中 bool show = _user.Add(user); #endregion } } catch { throw (new ArgumentNullException()); } }
Pour implémenter l'AccessToken dans le code ci-dessus , créez simplement une nouvelle classe Context
private static DateTime GetAccessToken_Time; /// 631fb227578dfffda61e1fa4d04b7d25 /// 过期时间为7200秒 /// 039f3e95db2a684c7b74365531eb6044 private static int Expires_Period = 7200; /// 631fb227578dfffda61e1fa4d04b7d25 /// /// 039f3e95db2a684c7b74365531eb6044 private static string mAccessToken; public static string AppID = "换成相应公众号的即可"; public static string AppSecret = "换成相应公众号的即可"; /// 631fb227578dfffda61e1fa4d04b7d25 /// 调用获取ACCESS_TOKEN,包含判断是否过期 /// 039f3e95db2a684c7b74365531eb6044 public static string AccessToken { get { //如果为空,或者过期,需要重新获取 if (string.IsNullOrEmpty(mAccessToken) || HasExpired()) { //获取access_token mAccessToken = GetAccessToken(AppID, AppSecret); } return mAccessToken; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 获取ACCESS_TOKEN方法 /// 039f3e95db2a684c7b74365531eb6044 /// d6dd8ceebd14bc425aa6d108b5f4eca38bb7487ae6a16a43571bc14c7fcf93c2 /// 50cac99ccafb21bc0689901ed6e5eb668bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 private static string GetAccessToken(string appId, string appSecret) { string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret); string result = HttpUtility.GetData(url); XDocument doc = XmlUtility.ParseJson(result, "root"); XElement root = doc.Root; if (root != null) { XElement access_token = root.Element("access_token"); if (access_token != null) { GetAccessToken_Time = DateTime.Now; if (root.Element("expires_in") != null) { Expires_Period = int.Parse(root.Element("expires_in").Value); } return access_token.Value; } else { GetAccessToken_Time = DateTime.MinValue; } } return null; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 判断Access_token是否过期 /// 039f3e95db2a684c7b74365531eb6044 /// 2363942ed0d6cd3e85bae1dffa568116boolf7735d9f6a7af371769ab5c16d23b2f3 private static bool HasExpired() { if (GetAccessToken_Time != null) { //过期时间,允许有一定的误差,一分钟。获取时间消耗 if (DateTime.Now > GetAccessToken_Time.AddSeconds(Expires_Period).AddSeconds(-60)) { return true; } } return false; }
GetData的实现
public static string GetData(string url) { return SendGetHttpRequest(url, "application/x-www-form-urlencoded"); }
ParseJson的实现
public static XDocument ParseJson(string json, string rootName) { return JsonConvert.DeserializeXNode(json, rootName); }
Concernant la troisième étape, il existe d'autres méthodes d'assistance publique dans la classe HttpUtility. sont publiés ici et peuvent être appelés
/// 631fb227578dfffda61e1fa4d04b7d25 /// 发送请求 /// 039f3e95db2a684c7b74365531eb6044 /// 0ab5e68b8f5d292e9a5f810a0a5b2929Url地址8bb7487ae6a16a43571bc14c7fcf93c2 /// c8a98340aded2d5f70b63a18be4bcac7数据8bb7487ae6a16a43571bc14c7fcf93c2 public static string SendHttpRequest(string url, string data) { return SendPostHttpRequest(url, "application/x-www-form-urlencoded", data); } /// 631fb227578dfffda61e1fa4d04b7d25 /// /// 039f3e95db2a684c7b74365531eb6044 /// 0ab5e68b8f5d292e9a5f810a0a5b29298bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string GetData(string url) { return SendGetHttpRequest(url, "application/x-www-form-urlencoded"); } /// 631fb227578dfffda61e1fa4d04b7d25 /// 发送请求 /// 039f3e95db2a684c7b74365531eb6044 /// 0ab5e68b8f5d292e9a5f810a0a5b2929Url地址8bb7487ae6a16a43571bc14c7fcf93c2 /// 7ac84fe36b5243e1cfce422579e18326方法(post或get)8bb7487ae6a16a43571bc14c7fcf93c2 /// 7ac84fe36b5243e1cfce422579e18326数据类型8bb7487ae6a16a43571bc14c7fcf93c2 /// f46925ffb3310f776e18deb091104d79数据8bb7487ae6a16a43571bc14c7fcf93c2 public static string SendPostHttpRequest(string url, string contentType, string requestData) { WebRequest request = (WebRequest)HttpWebRequest.Create(url); request.Method = "POST"; byte[] postBytes = null; request.ContentType = contentType; postBytes = Encoding.UTF8.GetBytes(requestData); request.ContentLength = postBytes.Length; using (Stream outstream = request.GetRequestStream()) { outstream.Write(postBytes, 0, postBytes.Length); } string result = string.Empty; using (WebResponse response = request.GetResponse()) { if (response != null) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } } return result; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 发送请求 /// 039f3e95db2a684c7b74365531eb6044 /// 0ab5e68b8f5d292e9a5f810a0a5b2929Url地址8bb7487ae6a16a43571bc14c7fcf93c2 /// 7ac84fe36b5243e1cfce422579e18326方法(post或get)8bb7487ae6a16a43571bc14c7fcf93c2 /// 7ac84fe36b5243e1cfce422579e18326数据类型8bb7487ae6a16a43571bc14c7fcf93c2 /// f46925ffb3310f776e18deb091104d79数据8bb7487ae6a16a43571bc14c7fcf93c2 public static string SendGetHttpRequest(string url, string contentType) { WebRequest request = (WebRequest)HttpWebRequest.Create(url); request.Method = "GET"; request.ContentType = contentType; string result = string.Empty; using (WebResponse response = request.GetResponse()) { if (response != null) { using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } } } } return result; }
Voir le code
Par. de la manière, l'utilisateur utilisé dans l'article ci-dessus La classe est la suivante
public class Users { /// 631fb227578dfffda61e1fa4d04b7d25 /// 全局凭证唯一Id /// 039f3e95db2a684c7b74365531eb6044 public string OpenID { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 公众号Id /// 039f3e95db2a684c7b74365531eb6044 public string PublicId { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 用户Id /// 039f3e95db2a684c7b74365531eb6044 public string UserID { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 昵称 /// 039f3e95db2a684c7b74365531eb6044 public string NickName { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 性别 1是男 0是女 /// 039f3e95db2a684c7b74365531eb6044 public int Sex { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 是否关注 1是关注 /// 039f3e95db2a684c7b74365531eb6044 public int Subscribe { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 国家 /// 039f3e95db2a684c7b74365531eb6044 public string Country { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 地区 /// 039f3e95db2a684c7b74365531eb6044 public string Province { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 城市 /// 039f3e95db2a684c7b74365531eb6044 public string City { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 关注时间 /// 039f3e95db2a684c7b74365531eb6044 public DateTime CreateDate { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 用户头像 /// 039f3e95db2a684c7b74365531eb6044 public string HeadimgUrl { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 第三方平台Id,可为空 /// 039f3e95db2a684c7b74365531eb6044 public string UnionID { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 用户取消关注时间 /// 039f3e95db2a684c7b74365531eb6044 public DateTime Un_Subscribe_Time { get; set; } }
Il y a 10 éléments de données dans la base de données en ce moment. Lorsque vous cliquez sur ce compte public, les informations de base de cet utilisateur sont stockées dans la base de données, elles deviennent 11 éléments de données
Processus d'autorisation de la page Web Pour une introduction détaillée, vous pouvez toujours vous référer au document du site officiel : Autorisation de la page WebLa première étape consiste à déterminer si l'utilisateur est autorisé. Sinon, passez ensuite à la page d'autorisation. S'il est autorisé, obtenez les informations de baseCode principal/// 631fb227578dfffda61e1fa4d04b7d25 /// 获取授权用户的基本信息,包括头像,姓名,等等(推荐方法) /// 039f3e95db2a684c7b74365531eb6044 /// 25fcf4a155410a35bb92f6672225e602用户授权之后的accessToken8bb7487ae6a16a43571bc14c7fcf93c2 /// 69f6963a53f2b062886c2f8bda5b040c用户授权之后的openid8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static ShouQuanWeiXinUserInfo GetShouQuanMessage() { //先判断是否有获取到用户授权的Code,HttpContext.Current.Session["ShouquanCode"] if (HttpContext.Current.Session["ShouquanCode"] == null|| HttpContext.Current.Session["ShouquanCode"].ToString()=="") { HttpContext.Current.Session["ShouquanCode"] = "123"; //用户授权的Code GetShouQuanCodeUrl(HttpContext.Current.Request.Url.AbsoluteUri); } else if(HttpContext.Current.Request.QueryString["code"] == null || HttpContext.Current.Request.QueryString["code"] == "") { //用户授权的Code GetShouQuanCodeUrl(HttpContext.Current.Request.Url.AbsoluteUri); } else { var model = ShouQuanAccessToken(HttpContext.Current.Request.QueryString["code"]); var url = $"http://www.php.cn/{model.access_token}&openid={model.openid}&lang=zh_CN"; string gethtml = MyHttpHelper.HttpGet(url); var ac = JsonHelpers.ToObject40e1c272594a55af5d8f3e794dcde9cb(gethtml); return ac; } return null; }
où , la méthode de code pour l'autorisation de l'utilisateur est la suivante :
/// 631fb227578dfffda61e1fa4d04b7d25 /// 重新获取用户授权的Code,可以获取用户的基本信息(头像,姓名,等等)(推荐用的方法) /// 039f3e95db2a684c7b74365531eb6044 /// 0ab5e68b8f5d292e9a5f810a0a5b2929目标Url8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static void GetShouQuanCodeUrl(string url) { string CodeUrl = ""; //加密过的url string value = HttpUtility.UrlEncode(url); //用户授权后的Code CodeUrl = $"http://www.php.cn/{Appid}&redirect_uri={value}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; System.Web.HttpContext.Current.Response.Redirect(CodeUrl);//先跳转到微信的服务器,取得code后会跳回来这页面的 }
Parmi elles, la méthode ShouQuanAccessToken
/// 631fb227578dfffda61e1fa4d04b7d25 //用户授权之后,获取授权的Access_Token与基本的Access_Token是不同的(推荐方法) /// 039f3e95db2a684c7b74365531eb6044 /// 779fe2e004f04a7d008a46e470a37e15用户授权之后的Code8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static OauthAccessToken ShouQuanAccessToken(string code) { var url = $"http://www.php.cn/{Appid}&secret={Secret}&code={code}&grant_type=authorization_code"; string gethtml = MyHttpHelper.HttpGet(url); OauthAccessToken ac = new OauthAccessToken(); ac = JsonHelpers.ToObjectae04fe4e8e60d0cd6884ddec311b9ab2(gethtml); return ac; }
Entité utilisateur
public class OauthAccessToken { public string access_token { get; set; } public string expires_in { get; set; } public string refresh_token { get; set; } public string openid { get; set; } public string scope { get; set; } }
MyHttpHelper public utilisé dans celui-ci La classe est la suivante
/// 631fb227578dfffda61e1fa4d04b7d25 /// Http连接操作帮助类 /// 039f3e95db2a684c7b74365531eb6044 public class HttpHelpers { #region 预定义方法或者变更 //默认的编码 private Encoding encoding = Encoding.Default; //Post数据编码 private Encoding postencoding = Encoding.Default; //HttpWebRequest对象用来发起请求 private HttpWebRequest request = null; //获取影响流的数据对象 private HttpWebResponse response = null; /// 631fb227578dfffda61e1fa4d04b7d25 /// 根据相传入的数据,得到相应页面数据 /// 039f3e95db2a684c7b74365531eb6044 /// 05e71af9e0b602a2910d46be96e57b62参数类对象8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116返回HttpResult类型f7735d9f6a7af371769ab5c16d23b2f3 public HttpResult GetHtml(HttpItem item) { //返回参数 HttpResult result = new HttpResult(); try { //准备参数 SetRequest(item); } catch (Exception ex) { return new HttpResult() { Cookie = string.Empty, Header = null, Html = ex.Message, StatusDescription = "配置参数时出错:" + ex.Message }; } try { #region 得到请求的response using (response = (HttpWebResponse)request.GetResponse()) { result.StatusCode = response.StatusCode; result.StatusDescription = response.StatusDescription; result.Header = response.Headers; if (response.Cookies != null) result.CookieCollection = response.Cookies; if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"]; byte[] ResponseByte = null; using (MemoryStream _stream = new MemoryStream()) { //GZIIP处理 if (response.ContentEncoding != null && response.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase)) { //开始读取流并设置编码方式 new GZipStream(response.GetResponseStream(), CompressionMode.Decompress).CopyTo(_stream, 10240); } else { //开始读取流并设置编码方式 response.GetResponseStream().CopyTo(_stream, 10240); } //获取Byte ResponseByte = _stream.ToArray(); } if (ResponseByte != null & ResponseByte.Length > 0) { //是否返回Byte类型数据 if (item.ResultType == ResultType.Byte) result.ResultByte = ResponseByte; //从这里开始我们要无视编码了 if (encoding == null) { Match meta = Regex.Match(Encoding.Default.GetString(ResponseByte), "a5b1e796d75a4e1f1df2b763c468d38e 1) ? meta.Groups[2].Value.ToLower().Trim() : string.Empty; if (c.Length > 2) { try { if (c.IndexOf(" ") > 0) c = c.Substring(0, c.IndexOf(" ")); encoding = Encoding.GetEncoding(c.Replace("\"", "").Replace("'", "").Replace(";", "").Replace("iso-8859-1", "gbk").Trim()); } catch { if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8; else encoding = Encoding.GetEncoding(response.CharacterSet); } } else { if (string.IsNullOrEmpty(response.CharacterSet)) encoding = Encoding.UTF8; else encoding = Encoding.GetEncoding(response.CharacterSet); } } //得到返回的HTML result.Html = encoding.GetString(ResponseByte); } else { //得到返回的HTML //result.Html = "本次请求并未返回任何数据"; result.Html = ""; } } #endregion } catch (WebException ex) { //这里是在发生异常时返回的错误信息 response = (HttpWebResponse)ex.Response; result.Html = ex.Message; if (response != null) { result.StatusCode = response.StatusCode; result.StatusDescription = response.StatusDescription; } } catch (Exception ex) { result.Html = ex.Message; } if (item.IsToLower) result.Html = result.Html.ToLower(); return result; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 为请求准备参数 /// 039f3e95db2a684c7b74365531eb6044 ///05e71af9e0b602a2910d46be96e57b62参数列表8bb7487ae6a16a43571bc14c7fcf93c2 private void SetRequest(HttpItem item) { // 验证证书 SetCer(item); //设置Header参数 if (item.Header != null && item.Header.Count > 0) foreach (string key in item.Header.AllKeys) { request.Headers.Add(key, item.Header[key]); } // 设置代理 //SetProxy(item); if (item.ProtocolVersion != null) request.ProtocolVersion = item.ProtocolVersion; request.ServicePoint.Expect100Continue = item.Expect100Continue; //请求方式Get或者Post request.Method = item.Method; request.Timeout = item.Timeout; request.KeepAlive = item.KeepAlive; request.ReadWriteTimeout = item.ReadWriteTimeout; if (!string.IsNullOrWhiteSpace(item.Host)) { request.Host = item.Host; } //Accept request.Accept = item.Accept; //ContentType返回类型 request.ContentType = item.ContentType; //UserAgent客户端的访问类型,包括浏览器版本和操作系统信息 request.UserAgent = item.UserAgent; // 编码 encoding = item.Encoding; //设置安全凭证 request.Credentials = item.ICredentials; //设置Cookie SetCookie(item); //来源地址 request.Referer = item.Referer; //是否执行跳转功能 request.AllowAutoRedirect = item.Allowautoredirect; //设置Post数据 SetPostData(item); //设置最大连接 if (item.Connectionlimit > 0) request.ServicePoint.ConnectionLimit = item.Connectionlimit; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置证书 /// 039f3e95db2a684c7b74365531eb6044 /// 05e71af9e0b602a2910d46be96e57b628bb7487ae6a16a43571bc14c7fcf93c2 private void SetCer(HttpItem item) { if (!string.IsNullOrWhiteSpace(item.CerPath)) { //这一句一定要写在创建连接的前面。使用回调的方法进行证书验证。 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); //初始化对像,并设置请求的URL地址 request = (HttpWebRequest)WebRequest.Create(item.URL); SetCerList(item); //将证书添加到请求里 request.ClientCertificates.Add(new X509Certificate(item.CerPath)); } else { //初始化对像,并设置请求的URL地址 request = (HttpWebRequest)WebRequest.Create(item.URL); SetCerList(item); } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置多个证书 /// 039f3e95db2a684c7b74365531eb6044 /// 05e71af9e0b602a2910d46be96e57b628bb7487ae6a16a43571bc14c7fcf93c2 private void SetCerList(HttpItem item) { if (item.ClentCertificates != null && item.ClentCertificates.Count > 0) { foreach (X509Certificate c in item.ClentCertificates) { request.ClientCertificates.Add(c); } } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置Cookie /// 039f3e95db2a684c7b74365531eb6044 /// 05e71af9e0b602a2910d46be96e57b62Http参数8bb7487ae6a16a43571bc14c7fcf93c2 private void SetCookie(HttpItem item) { if (!string.IsNullOrEmpty(item.Cookie)) request.Headers[HttpRequestHeader.Cookie] = item.Cookie; //设置CookieCollection if (item.ResultCookieType == ResultCookieType.CookieCollection) { request.CookieContainer = new CookieContainer(); if (item.CookieCollection != null && item.CookieCollection.Count > 0) request.CookieContainer.Add(item.CookieCollection); } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置Post数据 /// 039f3e95db2a684c7b74365531eb6044 /// 05e71af9e0b602a2910d46be96e57b62Http参数8bb7487ae6a16a43571bc14c7fcf93c2 private void SetPostData(HttpItem item) { //验证在得到结果时是否有传入数据 if (request.Method.Trim().ToLower().Contains("post")) { if (item.PostEncoding != null) { postencoding = item.PostEncoding; } byte[] buffer = null; //写入Byte类型 if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0) { //验证在得到结果时是否有传入数据 buffer = item.PostdataByte; }//写入文件 else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrWhiteSpace(item.Postdata)) { StreamReader r = new StreamReader(item.Postdata, postencoding); buffer = postencoding.GetBytes(r.ReadToEnd()); r.Close(); } //写入字符串 else if (!string.IsNullOrWhiteSpace(item.Postdata)) { buffer = postencoding.GetBytes(item.Postdata); } if (buffer != null) { request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置代理 /// 039f3e95db2a684c7b74365531eb6044 /// 05e71af9e0b602a2910d46be96e57b62参数对象8bb7487ae6a16a43571bc14c7fcf93c2 private void SetProxy(HttpItem item) { bool isIeProxy = item.ProxyIp.ToLower().Contains("ieproxy"); if (!string.IsNullOrWhiteSpace(item.ProxyIp) && !isIeProxy) { //设置代理服务器 if (item.ProxyIp.Contains(":")) { string[] plist = item.ProxyIp.Split(':'); WebProxy myProxy = new WebProxy(plist[0].Trim(), Convert.ToInt32(plist[1].Trim())); //建议连接 myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd); //给当前请求对象 request.Proxy = myProxy; } else { WebProxy myProxy = new WebProxy(item.ProxyIp, false); //建议连接 myProxy.Credentials = new NetworkCredential(item.ProxyUserName, item.ProxyPwd); //给当前请求对象 request.Proxy = myProxy; } } else if (isIeProxy) { //设置为IE代理 } else { request.Proxy = item.WebProxy; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 回调验证证书问题 /// 039f3e95db2a684c7b74365531eb6044 /// 1543637098b9d407caada70f4ed744fa流对象8bb7487ae6a16a43571bc14c7fcf93c2 /// e9c7a6fbabc4ab0df639f98995e9992e证书8bb7487ae6a16a43571bc14c7fcf93c2 /// 87b7c0bc5f80db1d4eee4a0b94eb8f8bX509Chain8bb7487ae6a16a43571bc14c7fcf93c2 /// b390182cf95cb554ca2d590591afa8cbSslPolicyErrors8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116boolf7735d9f6a7af371769ab5c16d23b2f3 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; } #endregion } /// 631fb227578dfffda61e1fa4d04b7d25 /// Http请求参考类 /// 039f3e95db2a684c7b74365531eb6044 public class HttpItem { /// 631fb227578dfffda61e1fa4d04b7d25 /// 请求URL必须填写 /// 039f3e95db2a684c7b74365531eb6044 public string URL { get; set; } string _Method = "GET"; /// 631fb227578dfffda61e1fa4d04b7d25 /// 请求方式默认为GET方式,当为POST方式时必须设置Postdata的值 /// 039f3e95db2a684c7b74365531eb6044 public string Method { get { return _Method; } set { _Method = value; } } int _Timeout = 100000; /// 631fb227578dfffda61e1fa4d04b7d25 /// 默认请求超时时间 /// 039f3e95db2a684c7b74365531eb6044 public int Timeout { get { return _Timeout; } set { _Timeout = value; } } int _ReadWriteTimeout = 30000; /// 631fb227578dfffda61e1fa4d04b7d25 /// 默认写入Post数据超时间 /// 039f3e95db2a684c7b74365531eb6044 public int ReadWriteTimeout { get { return _ReadWriteTimeout; } set { _ReadWriteTimeout = value; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置Host的标头信息 /// 039f3e95db2a684c7b74365531eb6044 public string Host { get; set; } Boolean _KeepAlive = true; /// 631fb227578dfffda61e1fa4d04b7d25 /// 获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接默认为true。 /// 039f3e95db2a684c7b74365531eb6044 public Boolean KeepAlive { get { return _KeepAlive; } set { _KeepAlive = value; } } string _Accept = "text/html, application/xhtml+xml, */*"; /// 631fb227578dfffda61e1fa4d04b7d25 /// 请求标头值 默认为text/html, application/xhtml+xml, */* /// 039f3e95db2a684c7b74365531eb6044 public string Accept { get { return _Accept; } set { _Accept = value; } } string _ContentType = "text/html"; /// 631fb227578dfffda61e1fa4d04b7d25 /// 请求返回类型默认 text/html /// 039f3e95db2a684c7b74365531eb6044 public string ContentType { get { return _ContentType; } set { _ContentType = value; } } string _UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)"; /// 631fb227578dfffda61e1fa4d04b7d25 /// 客户端访问信息默认Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0) /// 039f3e95db2a684c7b74365531eb6044 public string UserAgent { get { return _UserAgent; } set { _UserAgent = value; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 返回数据编码默认为NUll,可以自动识别,一般为utf-8,gbk,gb2312 /// 039f3e95db2a684c7b74365531eb6044 public Encoding Encoding { get; set; } private PostDataType _PostDataType = PostDataType.String; /// 631fb227578dfffda61e1fa4d04b7d25 /// Post的数据类型 /// 039f3e95db2a684c7b74365531eb6044 public PostDataType PostDataType { get { return _PostDataType; } set { _PostDataType = value; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// Post请求时要发送的字符串Post数据 /// 039f3e95db2a684c7b74365531eb6044 public string Postdata { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// Post请求时要发送的Byte类型的Post数据 /// 039f3e95db2a684c7b74365531eb6044 public byte[] PostdataByte { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// Cookie对象集合 /// 039f3e95db2a684c7b74365531eb6044 public CookieCollection CookieCollection { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 请求时的Cookie /// 039f3e95db2a684c7b74365531eb6044 public string Cookie { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 来源地址,上次访问地址 /// 039f3e95db2a684c7b74365531eb6044 public string Referer { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 证书绝对路径 /// 039f3e95db2a684c7b74365531eb6044 public string CerPath { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置代理对象,不想使用IE默认配置就设置为Null,而且不要设置ProxyIp /// 039f3e95db2a684c7b74365531eb6044 public WebProxy WebProxy { get; set; } private Boolean isToLower = false; /// 631fb227578dfffda61e1fa4d04b7d25 /// 是否设置为全文小写,默认为不转化 /// 039f3e95db2a684c7b74365531eb6044 public Boolean IsToLower { get { return isToLower; } set { isToLower = value; } } private Boolean allowautoredirect = false; /// 631fb227578dfffda61e1fa4d04b7d25 /// 支持跳转页面,查询结果将是跳转后的页面,默认是不跳转 /// 039f3e95db2a684c7b74365531eb6044 public Boolean Allowautoredirect { get { return allowautoredirect; } set { allowautoredirect = value; } } private int connectionlimit = 1024; /// 631fb227578dfffda61e1fa4d04b7d25 /// 最大连接数 /// 039f3e95db2a684c7b74365531eb6044 public int Connectionlimit { get { return connectionlimit; } set { connectionlimit = value; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 代理Proxy 服务器用户名 /// 039f3e95db2a684c7b74365531eb6044 public string ProxyUserName { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 代理 服务器密码 /// 039f3e95db2a684c7b74365531eb6044 public string ProxyPwd { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 代理 服务IP,如果要使用IE代理就设置为ieproxy /// 039f3e95db2a684c7b74365531eb6044 public string ProxyIp { get; set; } private ResultType resulttype = ResultType.String; /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置返回类型String和Byte /// 039f3e95db2a684c7b74365531eb6044 public ResultType ResultType { get { return resulttype; } set { resulttype = value; } } private WebHeaderCollection header = new WebHeaderCollection(); /// 631fb227578dfffda61e1fa4d04b7d25 /// header对象 /// 039f3e95db2a684c7b74365531eb6044 public WebHeaderCollection Header { get { return header; } set { header = value; } } /// 631fb227578dfffda61e1fa4d04b7d25 // 获取或设置用于请求的 HTTP 版本。返回结果:用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11。 /// 039f3e95db2a684c7b74365531eb6044 public Version ProtocolVersion { get; set; } private Boolean _expect100continue = true; /// 631fb227578dfffda61e1fa4d04b7d25 /// 获取或设置一个 System.Boolean 值,该值确定是否使用 100-Continue 行为。如果 POST 请求需要 100-Continue 响应,则为 true;否则为 false。默认值为 true。 /// 039f3e95db2a684c7b74365531eb6044 public Boolean Expect100Continue { get { return _expect100continue; } set { _expect100continue = value; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置509证书集合 /// 039f3e95db2a684c7b74365531eb6044 public X509CertificateCollection ClentCertificates { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 设置或获取Post参数编码,默认的为Default编码 /// 039f3e95db2a684c7b74365531eb6044 public Encoding PostEncoding { get; set; } private ResultCookieType _ResultCookieType = ResultCookieType.String; /// 631fb227578dfffda61e1fa4d04b7d25 /// Cookie返回类型,默认的是只返回字符串类型 /// 039f3e95db2a684c7b74365531eb6044 public ResultCookieType ResultCookieType { get { return _ResultCookieType; } set { _ResultCookieType = value; } } private ICredentials _ICredentials = CredentialCache.DefaultCredentials; /// 631fb227578dfffda61e1fa4d04b7d25 /// 获取或设置请求的身份验证信息。 /// 039f3e95db2a684c7b74365531eb6044 public ICredentials ICredentials { get { return _ICredentials; } set { _ICredentials = value; } } } /// 631fb227578dfffda61e1fa4d04b7d25 /// Http返回参数类 /// 039f3e95db2a684c7b74365531eb6044 public class HttpResult { /// 631fb227578dfffda61e1fa4d04b7d25 /// Http请求返回的Cookie /// 039f3e95db2a684c7b74365531eb6044 public string Cookie { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// Cookie对象集合 /// 039f3e95db2a684c7b74365531eb6044 public CookieCollection CookieCollection { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 返回的String类型数据 只有ResultType.String时才返回数据,其它情况为空 /// 039f3e95db2a684c7b74365531eb6044 public string Html { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 返回的Byte数组 只有ResultType.Byte时才返回数据,其它情况为空 /// 039f3e95db2a684c7b74365531eb6044 public byte[] ResultByte { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// header对象 /// 039f3e95db2a684c7b74365531eb6044 public WebHeaderCollection Header { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 返回状态说明 /// 039f3e95db2a684c7b74365531eb6044 public string StatusDescription { get; set; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 返回状态码,默认为OK /// 039f3e95db2a684c7b74365531eb6044 public HttpStatusCode StatusCode { get; set; } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 返回类型 /// 039f3e95db2a684c7b74365531eb6044 public enum ResultType { /// 631fb227578dfffda61e1fa4d04b7d25 /// 表示只返回字符串 只有Html有数据 /// 039f3e95db2a684c7b74365531eb6044 String, /// 631fb227578dfffda61e1fa4d04b7d25 /// 表示返回字符串和字节流 ResultByte和Html都有数据返回 /// 039f3e95db2a684c7b74365531eb6044 Byte } /// 631fb227578dfffda61e1fa4d04b7d25 /// Post的数据格式默认为string /// 039f3e95db2a684c7b74365531eb6044 public enum PostDataType { /// 631fb227578dfffda61e1fa4d04b7d25 /// 字符串类型,这时编码Encoding可不设置 /// 039f3e95db2a684c7b74365531eb6044 String, /// 631fb227578dfffda61e1fa4d04b7d25 /// Byte类型,需要设置PostdataByte参数的值编码Encoding可设置为空 /// 039f3e95db2a684c7b74365531eb6044 Byte, /// 631fb227578dfffda61e1fa4d04b7d25 /// 传文件,Postdata必须设置为文件的绝对路径,必须设置Encoding的值 /// 039f3e95db2a684c7b74365531eb6044 FilePath } /// 631fb227578dfffda61e1fa4d04b7d25 /// Cookie返回类型 /// 039f3e95db2a684c7b74365531eb6044 public enum ResultCookieType { /// 631fb227578dfffda61e1fa4d04b7d25 /// 只返回字符串类型的Cookie /// 039f3e95db2a684c7b74365531eb6044 String, /// 631fb227578dfffda61e1fa4d04b7d25 /// CookieCollection格式的Cookie集合同时也返回String类型的cookie /// 039f3e95db2a684c7b74365531eb6044 CookieCollection } /// 631fb227578dfffda61e1fa4d04b7d25HttpHelper的2次封装函数 作者: /// 039f3e95db2a684c7b74365531eb6044 public class MyHttpHelper { #region 公共函数 /// 631fb227578dfffda61e1fa4d04b7d25返回 HTML 字符串的编码结果039f3e95db2a684c7b74365531eb6044 /// afb41405c7ad14d83dafa7bbddb7f63d字符串8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116编码结果f7735d9f6a7af371769ab5c16d23b2f3 public static string HtmlEncode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } return str.Length > 0 ? HttpUtility.HtmlEncode(str) : ""; } /// 631fb227578dfffda61e1fa4d04b7d25返回 HTML 字符串的解码结果039f3e95db2a684c7b74365531eb6044 /// afb41405c7ad14d83dafa7bbddb7f63d字符串8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116解码结果f7735d9f6a7af371769ab5c16d23b2f3 public static string HtmlDecode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } return str.Length > 0 ? HttpUtility.HtmlDecode(str) : ""; } /// 631fb227578dfffda61e1fa4d04b7d25 /// 根据指定的编码对RUl进行解码 /// 039f3e95db2a684c7b74365531eb6044 /// afb41405c7ad14d83dafa7bbddb7f63d要解码的字符串8bb7487ae6a16a43571bc14c7fcf93c2 /// ef080b8f96d6b1bf28e6abae73047b3e要进行解码的编码方式8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string UrlDecode(string str, Encoding encoding = null) { if (string.IsNullOrEmpty(str)) { return ""; } if (str.Length == 0) { return ""; } if (encoding == null) { return HttpUtility.UrlDecode(str); } else { return HttpUtility.UrlDecode(str, encoding); } } /// 631fb227578dfffda61e1fa4d04b7d25根据指定的编码对URL进行编码039f3e95db2a684c7b74365531eb6044 /// afb41405c7ad14d83dafa7bbddb7f63d要编码的URL8bb7487ae6a16a43571bc14c7fcf93c2 /// ef080b8f96d6b1bf28e6abae73047b3e要进行编码的编码方式8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string UrlEncode(string str, Encoding encoding = null) { if (string.IsNullOrEmpty(str)) { return ""; } if (str.Length == 0) { return ""; } if (encoding == null) { return HttpUtility.UrlEncode(str); } else { return HttpUtility.UrlEncode(str, encoding); } } /// 631fb227578dfffda61e1fa4d04b7d25 /// 根据 charSet 返回 Encoding /// 039f3e95db2a684c7b74365531eb6044 /// e90987d9088447f21632e70dc5261059"gb2312" or "utf-8",默认: "" == "utf-8"8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static Encoding GetEncoding(string charSet) { Encoding en = Encoding.Default; if (charSet == "gb2312") { en = Encoding.GetEncoding("gb2312"); } else if (charSet == "utf-8") { en = Encoding.UTF8; } return en; } #endregion #region Post /// 631fb227578dfffda61e1fa4d04b7d25HTTP Get方式请求数据039f3e95db2a684c7b74365531eb6044 /// 0ab5e68b8f5d292e9a5f810a0a5b2929URL8bb7487ae6a16a43571bc14c7fcf93c2 /// 7531765eb83dfc8ac7e7b1c75b5063d2user=123123 & pwd=1231313"8bb7487ae6a16a43571bc14c7fcf93c2 /// e90987d9088447f21632e70dc5261059"gb2312" or "utf-8",默认: "" == "utf-8"8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string HttpPost(string url, string param, string charSet = "utf-8") { HttpHelpers http = new HttpHelpers(); HttpItem item = new HttpItem() { URL = url, Encoding = GetEncoding(charSet),//编码格式(utf-8,gb2312,gbk) 可选项 默认类会自动识别 Method = "post",//URL 可选项 默认为Get Postdata = param }; //得到HTML代码 HttpResult result = http.GetHtml(item); //取出返回的Cookie //string cookie = result.Cookie; //返回的Html内容 string html = result.Html; if (result.StatusCode == System.Net.HttpStatusCode.OK) { return html; } //string statusCodeDescription = result.StatusDescription; return ""; } #endregion #region Get /// 631fb227578dfffda61e1fa4d04b7d25HTTP Get方式请求数据039f3e95db2a684c7b74365531eb6044 /// 0ab5e68b8f5d292e9a5f810a0a5b2929URL8bb7487ae6a16a43571bc14c7fcf93c2 /// e90987d9088447f21632e70dc5261059"gb2312" or "utf-8",默认: "" == "utf-8"8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string HttpGet(string url, string charSet = "utf-8") { HttpHelpers http = new HttpHelpers(); HttpItem item = new HttpItem() { URL = url, Encoding = GetEncoding(charSet), Method = "get" }; //得到HTML代码 HttpResult result = http.GetHtml(item); //取出返回的Cookie //string cookie = result.Cookie; //返回的Html内容 string html = result.Html; if (result.StatusCode == System.Net.HttpStatusCode.OK) { return html; } //string statusCodeDescription = result.StatusDescription; return ""; } /// 631fb227578dfffda61e1fa4d04b7d25POST客服消息/summary> /// 0ab5e68b8f5d292e9a5f810a0a5b2929URL8bb7487ae6a16a43571bc14c7fcf93c2 /// 6f8056bc71f11d4440ce6d7baf9b1b39内容8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116消息状态f7735d9f6a7af371769ab5c16d23b2f3 public static string GetPage(string posturl, string postData) { Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte[] data = encoding.GetBytes(postData); // 准备请求... try { // 设置参数 request = WebRequest.Create(posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer(); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; outstream = request.GetRequestStream(); outstream.Write(data, 0, data.Length); outstream.Close(); //发送请求并获取相应回应数据 response = request.GetResponse() as HttpWebResponse; //直到request.GetResponse()程序才开始向目标网页发送Post请求 instream = response.GetResponseStream(); sr = new StreamReader(instream, encoding); //返回结果网页(html)代码 string content = sr.ReadToEnd(); string err = string.Empty; return content; } catch (Exception ex) { string err = ex.Message; return err; } } #endregion }
La classe JsonHelpers encapsulée est la suivante
#region 通用 /// 631fb227578dfffda61e1fa4d04b7d25检查字符串是否json格式039f3e95db2a684c7b74365531eb6044 /// dbd0958913b860a4a8afa7345b0262d98bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static bool IsJson(string jText) { if (string.IsNullOrEmpty(jText) || jText.Length < 3) { return false; } if (jText.Substring(0, 2) == "{\"" || jText.Substring(0, 3) == "[{\"") { return true; } return false; } /// 631fb227578dfffda61e1fa4d04b7d25检查字符串是否json格式数组039f3e95db2a684c7b74365531eb6044 /// dbd0958913b860a4a8afa7345b0262d98bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static bool IsJsonRs(string jText) { if (string.IsNullOrEmpty(jText) || jText.Length < 3) { return false; } if (jText.Substring(0, 3) == "[{\"") { return true; } return false; } /// 631fb227578dfffda61e1fa4d04b7d25格式化 json039f3e95db2a684c7b74365531eb6044 /// dbd0958913b860a4a8afa7345b0262d98bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string Fmt_Null(string jText) { return StringHelper.ReplaceString(jText, ":null,", ":\"\",", true); } /// 631fb227578dfffda61e1fa4d04b7d25格式化 json ,删除左右二边的[]039f3e95db2a684c7b74365531eb6044 /// dbd0958913b860a4a8afa7345b0262d98bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string Fmt_Rs(string jText) { jText = jText.Trim(); jText = jText.Trim('['); jText = jText.Trim(']'); return jText; } #endregion #region Json序列化 /// 631fb227578dfffda61e1fa4d04b7d25序列化039f3e95db2a684c7b74365531eb6044 /// 9eeacba56bab5a25cf1fbc370b62c92fobject 8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string ToJson(object obj) { var idtc = new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" }; return JsonConvert.SerializeObject(obj, idtc); } /// 631fb227578dfffda61e1fa4d04b7d25序列化--sql039f3e95db2a684c7b74365531eb6044 /// b35bf2334f45239da9b4babfd5238c27DataTable8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static string ToJson_FromSQL(DataTable dt) { string ss = ToJson(dt); dt.Dispose(); return ss; } #endregion #region Json反序列化 /// 631fb227578dfffda61e1fa4d04b7d25反序列化039f3e95db2a684c7b74365531eb6044 /// dbd0958913b860a4a8afa7345b0262d98bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116f7735d9f6a7af371769ab5c16d23b2f3 public static DataTable ToDataTable(string jText) { if (string.IsNullOrEmpty(jText)) { return null; } else { try { return JsonConvert.DeserializeObjectb9be6be499e4aef49099cdb77f79b721(jText); } catch { return null; } } } /// 631fb227578dfffda61e1fa4d04b7d25反序列化039f3e95db2a684c7b74365531eb6044 /// d65706098b2250eee2f48a758c9680c8类型8ed7e392d75469626ca6a252f320a704 /// dbd0958913b860a4a8afa7345b0262d9json字符串8bb7487ae6a16a43571bc14c7fcf93c2 /// 2363942ed0d6cd3e85bae1dffa568116类型数据f7735d9f6a7af371769ab5c16d23b2f3 public static T ToObject8742468051c85b06f0a0af9e3e506b5c(string jText) { return (T)JsonConvert.DeserializeObject(jText, typeof(T)); } #endregion
Parmi eux, s'il s'agit de VS2015 ou inférieur, vous pouvez changer la chaîne d'url à la méthode string.format("")
Appeler la méthode de valeur
Affichage de l'effet
Pour plus d'autorisation de page Web de développement de compte public WeChat Pour obtenir des informations de base sur l'utilisateur, veuillez faire attention au site Web PHP chinois pour les articles connexes !