微信通过openID发送消息/后台post、get提交并接收数据

 
控制器:下面是post发送消息(微信不支持从前台发送数据,之前试过,报错,需要跨域,跨域的问题解决后还不行,最后发现之后后端提交
WXApi类:
#region 验证Token是否过期
        /// <summary>
        ///  验证Token是否过期
        ///</summary>
        public static bool TokenExpired(string access_token)
        {
            string jsonStr = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", access_token));
            if (Tools.GetJsonValue(jsonStr, "errcode") == "42001")
            {
                return true;
            }
            return false;
        }
        #endregion
        #region 获取Token
        /// <summary>
        ///  获取Token
        /// </summary>
        public static string GetToken(string appid, string secret)
        {
            string strJson = HttpRequestUtil.RequestUrl(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));
            return Tools.GetJsonValue(strJson, "access_token");
        }
        #endregion

Tools类:
 #region 获取Json字符串某节点的值
        /// <summary>
        /// /// 获取Json字符串某节点的值
        /// /// </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)
                {
                    //先截逗号,若是最后一个,截“}”号,取最小值
                    int end = jsonStr.IndexOf(',', index); if (end == -1)
                    {
                        end = jsonStr.IndexOf('}', index);
                    }
                    result = jsonStr.Substring(index, end - index);
                    result = result.Trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
                }
            }
            return result;
        }
        #endregion
HttpRequestUtil类:
 #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url)
        {
            return RequestUrl(url, "POST");
        }
        #endregion
        #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url, string method)
        {
            // 设置参数
            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.GetRequestStream()
            //request.
            request.Headers.Add("charset", "utf-8");  //发送请求并获取相应回应数据
            Stream postStream = request.GetRequestStream();
            //postStream.Write(,0,bytearra)
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;//直到request.GetResponse()程序才开始向目标网页发送Post请求
            //Stream responseStream =
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);//返回结果网页(html)代码
            string content = sr.ReadToEnd();
            return content;
        }
        #endregion
        
下面是会返回错误44002的:原因是post数据未发送(没有提交数据),也是控制器中:
  #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url)
        {
            return RequestUrl(url, "POST");
        }
        #endregion
        #region 请求Url,不发送数据
        /// <summary>
        /// 请求Url,不发送数据
        /// </summary>
        public static string RequestUrl(string url, string method)
        {
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = method;
            request.ContentType = "textml";
            request.Headers.Add("charset", "utf-8");  //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            Stream responseStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
            //返回结果网页(html)代码
            string content = sr.ReadToEnd();
            return content;
        }
        #endregion
)
 #region
        public string send(string openida, string senddata)
        {
            string posturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WXApi.GetToken(appID, appsecret);//发送地址
            string postData = "{\"touser\":\"" + openida + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + senddata + "\"}}";//发送消息的字符串 openida为openid,senddata为发送内容
            return GetPage(posturl, postData);//以post的形式发送出去
        }
        #endregion
        #region
        public string GetPage(string posturl, string postData)///向微信服务器发送post请求(主要是发送消息)
        {
            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";//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;
                //Response.Write(err);
                //return string.Empty;
                return err;
            }
        }
        #endregion
获取AppID和:appsecret ,(在控制器上面写上)
     public static readonly string appID = ConfigurationManager.AppSettings["appID"];
        public static readonly string appsecret = ConfigurationManager.AppSettings["appsecret"];
web.config中需要写入下面信息:
 <appSettings>
    <add key="appID" value="wxf39b0be4b27f0016" />
    <add key="appsecret" value="667b57fe3f9126b4c0960b1300c858db" />
 </appSettings>

C# .NET 配置404,500等错误信息

 
<customErrors mode="On" defaultRedirect="viewAll.html"><!--所有的错误显示页-->
     <error statusCode="403" redirect="view403.html" /><!--针对403的错误页-->
     <error statusCode="404" redirect="view404.html" /><!---针对404的错误页-->    <error statusCode="500" redirect="view500.html  /"><!--针对500的错误页-->
</customErrors>

连接字符串

 
<connectionStrings>
    <add name="ConnectionStrings" connectionString="Data Source=192.168.3.2;port=3306;Initial Catalog=tsyw;user id=root;password=123456;Charset=utf8"     providerName="MySql.Data.MySqlClient" />
    <add name="ConnectionStrings" connectionString="Data Source=192.168.3.2;Initial Catalog=TSYW;User ID=sa;Password=AAbb123456;Persist Security Info     =True;" providerName="System.Data.SqlClient" />
  <add name="ConnectionStrings" connectionString="data source=X450V-PC;initial catalog=TSYW;integrated security=True;MultipleActiveResultSets=True;    App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>

微信通过openID发送消息/后台post、get提交并接收数据 C# .NET 配置404,500等错误信息 连接字符串的更多相关文章

  1. 微信通过openID发送消息/后台post、get提交并接收数据

    控制器:下面是post发送消息(微信不支持从前台发送数据,之前试过,报错,需要跨域,跨域的问题解决后还不行,最后发现之后后端提交 WXApi类: #region 验证Token是否过期 /// < ...

  2. 通过企业微信API接口发送消息

    最近给公司测试组内部开发一个记账小工具,当账目出现问题的时候需要发送消息通知大家,前期主要采用的QQ发送通知消息,但是有一天突然无法连接到QQ服务器,运维的同学建议采用微信的方式对接然后进行告警,所以 ...

  3. 微信公众号发送消息模板(java)

    这段时间接触公众号开发,写下向用户发送消息模板的接口调用 先上接口代码 public static JSONObject sendModelMessage(ServletContext context ...

  4. Python 微信公众号发送消息

    1. 公众号测试地址 https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index 2. ...

  5. .Net HttpClient 模拟登录微信公众平台发送消息

    1.模拟登录 public WeiXinRetInfo ExecLogin(string name, string pass) { CookieContainer cc = new CookieCon ...

  6. 微信公众号发送消息给用户 php

    1.微信公众号 这里得话 一开始先去看了 微信公众号的接口 发现网页授权需要时认证的服务号,一开始想的是那去申请一个认证的服务号岂不是很费事,然后网上搜了搜,发现了还有微信公众号个人测试号这个东西,所 ...

  7. 公众号用户发送消息后台PHP回复没有反应的解决办法

    1.问题:微信公众平台官方提供下载的示例代码中,使用$postStr =$GLOBALS["HTTP_RAW_POST_DATA"];来获取微信服务器推送的消息数据.但是有的开发者 ...

  8. axios发送post请求,如何提交表单数据?

    axios发送post请求,提交表单数据的方式 默认情况下,axios将JavaScript对象序列化为JSON.要以application / x-www-form-urlencoded格式发送数据 ...

  9. 前端页面传来数组,后台用对象集合list接收数据的写法

    //保存页面显示应用$("#save").click(function(){ var data = [{"applicationtypeid":"65 ...

随机推荐

  1. 自定义tableView通用MVC设计

  2. 优化UITableView

    在iOS应用中,UITableView应该是使用率最高的视图之一了.iPod.时钟.日历.备忘录.Mail.天气.照片.电话.短信.Safari.App Store.iTunes.Game Cente ...

  3. cc.Component

    组件入口函数1: onLoad: 组件加载的时候调用, 保证了你可以获取到场景中的其他节点,以及节点关联的资源数据;2: start: 也就是第一次执行 update 之前触发;3: update(d ...

  4. Vue微信自定义分享时安卓系统config:ok,ios系统config:invalid signature签名错误,或者安卓和ios二次分享时均config:ok但是分享无效的解决办法

    简述需求:要求指定页面可以进行微信自定义分享(自定义标题,描述,图片,链接),剩下的页面隐藏所有基础接口.二次分享依然可以正常使用,切换至其他页面也可以正常进行自定义分享. 这两天在做微信自定义分享的 ...

  5. [luoguP2622] 关灯问题II(状压最短路)

    传送门 本以为是状压DP,但是有后效性. 所以写一手状压spfa #include <queue> #include <cstdio> #include <cstring ...

  6. 巴蜀3540 -- 【Violet 6 最终话】蒲公英

    Description 原题的时间限制是 2s . 亲爱的哥哥: 你在那个城市里面过得好吗? 我在家里面最近很开心呢.昨天晚上奶奶给我讲了那个叫「绝望」的大坏蛋的故事的说!它把人们的房子和田地搞坏,还 ...

  7. [NOIP2003] 普及组

    乒乓球 模拟 /*By SilverN*/ #include<iostream> #include<algorithm> #include<cstring> #in ...

  8. 前端的指导方针---css篇

    英语是渣渣,想学英语,又不想花钱报培训班.看不懂的文章,还是翻译一下留着自己看吧. 引自   :  https://github.com/bendc/frontend-guidelines HTML ...

  9. hiho一下 第四十五周 博弈游戏·Nim游戏·二 [ 博弈 ]

    传送门 题目1 : 博弈游戏·Nim游戏·二 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 Alice和Bob这一次准备玩一个关于硬币的游戏:N枚硬币排成一列,有的正面 ...

  10. 工具--IIS Express

    iisexpress-proxy https://github.com/icflorescu/iisexpress-proxy 适用于联调,比如app调用接口,开启端口后,app调用接口后会直接进入端 ...