新建项目 -> ASP.NET空WEB应用程序网站(不要使用新建网站) 新建一般处理程序
#怎么操作SQL数据库不写了 只发一些关键部分代码
##一般处理程序关键代码
public class Interface : IHttpHandler
{
public static readonly string SqlConnectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;
public void ProcessRequest(HttpContext context)
{
string postString = string.Empty;
WXHelper myWXHelper = new WXHelper(SqlConnectionString);
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
{
using (Stream stream = HttpContext.Current.Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = Encoding.UTF8.GetString(postBytes);
if (!string.IsNullOrEmpty(postString))
{
/// <summary>
/// 处理信息并应答
/// </summary>
//Handle(postString);
}
}
}
else
{
/// <summary>
/// 微信接入验证
/// </summary>
myWXHelper.Auth();
}
}
/// <summary>
/// 处理信息并应答
/// </summary>
private void Handle(string postStr)
{
messageHelp help = new messageHelp(SqlConnectionString);
string responseContent = help.ReturnMessage(postStr);
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Write(responseContent);
}
public bool IsReusable
{
get
{
return false;
}
}
}
说明:
接入验证是GET,其他后续的消息都是POST方式。
WXHelper和messageHelper自己封装的2个类。
##WXHelper关键代码
private readonly string token = "按自己的填"; //按自己的填
//微信接入时对服务器的验证
public void Auth()
{
if (string.IsNullOrEmpty(token))
{
return;
}
string echoStr = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["signature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
if (!string.IsNullOrEmpty(echoStr))
{
string StrSQL = "";
using (SqlConnection mySqlConnection = new SqlConnection(mySqlConnectionString))
{
StrSQL = "INSERT INTO [WX_Auth] ([signature], [timestamp], [nonce], [echoStr], [FromIPAddress]) VALUES (";
StrSQL += "@signature, @timestamp, @nonce, @echoStr, @FromIPAddress)";
SqlCommand mySqlCommand = new SqlCommand(StrSQL, mySqlConnection);
mySqlCommand.Parameters.AddWithValue("@signature", signature);
mySqlCommand.Parameters.AddWithValue("@timestamp", timestamp);
mySqlCommand.Parameters.AddWithValue("@nonce", nonce);
mySqlCommand.Parameters.AddWithValue("@echoStr", echoStr);
mySqlCommand.Parameters.AddWithValue("@FromIPAddress", getIp());
mySqlConnection.Open();
mySqlCommand.ExecuteNonQuery();
mySqlConnection.Close();
}
HttpContext.Current.Response.Write(echoStr);
HttpContext.Current.Response.End();
}
}
//获取客户端的IP地址
public static string getIp()
{
if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(new char[] { ',' })[0];
else
return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
说明:
getIP()用来获取客户机的IP,这里当然获取微信验证服务器的IP
代码里把验证的请求信息写进了数据库,数据库创建对应的表
返回echoStr给微信验证服务器就算通过了
一次验证通不过多点几次,有时候微信验证服务器卡