asp.net Web API 接入微信公众平台验证服务器,接收微信发送的POST请求

验证签名,接入微信公众平台:不能直接返回String,直接返回String微信服务器不接受。

// GET: api/checkSignature/5
        public HttpResponseMessage Get(string signature , string timestamp , string nonce , string echostr)
        {

            string TOKEN = "微信公众平台设置的TOKEN";

            var response = new HttpResponseMessage(HttpStatusCode.OK);
            string[] ArrTmp = { TOKEN, timestamp, nonce };
            string result = "";
            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);
            string sign = SignHelper.Sha1Sign(tmpStr);
            Log.WorkInfo("sign:" + sign);
            Log.WorkInfo("signature:" + signature);
            if (sign.Equals(signature))
            {
                result =  echostr;
            }
            else
            {
                result =  "signature fail";
            }
            response.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
            return response;
        }
/// 
        /// Sha1加密签名
        /// 
        /// 
        /// 
        public static string Sha1Sign(string str)
        {
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_sha1_in = System.Text.UTF8Encoding.Default.GetBytes(str);
            byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
            string signature = BitConverter.ToString(bytes_sha1_out);
            signature = signature.Replace("-", "").ToLower();
            return signature;
        }

2.验证完服务器后,接收用户消息:这里不 能直接用[FromBody]接收参数。

 public HttpResponseMessage Post()
        {
            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
            byte[] b = new byte[s.Length];
            s.Read(b, 0, (int)s.Length);
            string postStr = Encoding.UTF8.GetString(b);
            Log.WorkInfo("接收时间:"+System.DateTime.Now.ToString("yyyy-mm-dd HH:MM:ss")+":"+postStr);
            //Log.WorkInfo(value);
            //return "";
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent("", System.Text.Encoding.UTF8, "text/plain");
            return response;
        }

如果您是土豪,请打赏一下吧!您的打赏是我不断努力的动力!

asp.net Web API 接入微信公众平台验证服务器,接收微信发送的POST请求_第1张图片asp.net Web API 接入微信公众平台验证服务器,接收微信发送的POST请求_第2张图片

你可能感兴趣的:(asp.net Web API 接入微信公众平台验证服务器,接收微信发送的POST请求)