验证消息的真实性
在mvc controller所在项目中添加过滤器,在过滤器中重写
public override void onactionexecuting(actionexecutingcontext filtercontext)方法
新建数据模型
注:服务器接收消息时,不再是signature而是msg_signature
微信服务器推送消息到服务器的http请求报文示例
post /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6×tamp=1409659813&nonce=1372623149 http/1.1
host: qy.weixin.qq.com
方法重写,实现对消息的验证
调用微信接入时验证的方法,不过参数需要小改动一下,采用新建的数据模型
在action方法或在controller上添加过滤器属性
代码示例
model
////// 微信推送消息模型 /// public class wechatmsgrequestmodel { public string timestamp { get; set; } public string nonce { get; set; } public string msg_signature { get; set; } }
filter
public class wechatrequestvalidattribute : actionfilterattribute
{
private const string token = "stupidme";
public override void onactionexecuting(actionexecutingcontext filtercontext)
{
//参数适配
model.formatmodel.wechatmsgrequestmodel model = new model.formatmodel.wechatmsgrequestmodel() { nonce= filtercontext.httpcontext.request.querystring["nonce"],msg_signature= filtercontext.httpcontext.request.querystring["msg_signature"],timestamp= filtercontext.httpcontext.request.querystring["timestamp"] };
//验证
if (checksignature(model))
{
base.onactionexecuting(filtercontext);
}
}
private bool checksignature(model.formatmodel.wechatmsgrequestmodel model)
{
string signature, timestamp, nonce, tempstr;
//获取请求来的参数
signature = model.msg_signature;
timestamp = model.timestamp;
nonce = model.nonce;
//创建数组,将 token, timestamp, nonce 三个参数加入数组
string[] array = { token, timestamp, nonce };
//进行排序
array.sort(array);
//拼接为一个字符串
tempstr = string.join("", array);
//对字符串进行 sha1加密
tempstr = formsauthentication.hashpasswordforstoringinconfigfile(tempstr, "sha1").tolower();
//判断signature 是否正确
if (tempstr.equals(signature))
{
return true;
}
else
{
return false;
}
}
}
controller code
////// 日志助手 /// private static common.loghelper logger = new common.loghelper(typeof(homecontroller)); [filters.wechatrequestvalid] public void valid(model.formatmodel.wechatmsgrequestmodel model) { if (modelstate.isvalid) { try { //判断是否是post请求 if (httpcontext.request.httpmethod.toupper() == "post") { //从请求的数据流中获取请求信息 using (stream stream = httpcontext.request.inputstream) { byte[] postbytes = new byte[stream.length]; stream.read(postbytes, 0, (int)stream.length); string poststring = system.text.encoding.utf8.getstring(postbytes); handle(poststring,model); } } } catch (exception ex) { logger.error("发生异常,异常信息:" ex.message ex.stacktrace); } } }
以上所述就是本文的全部内容 了,希望大家能够喜欢。
lost丶love