场景:
logger.Info("f: " + wx.From);
logger.Info("c: " + wx.Code); logger.Info("s: " + wx.State);Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=8RAN90uJ1967wpt1Y5&redirect_uri=www.xxxx.com%3a8001%2fWxAuthPage.aspx?from=notreserve&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
出现:
除了code不一致,其它一致。
这样导致如下两次插入:
var mealtake = new MealTake
{ Id = Guid.NewGuid(), IsTaked = true, TakeDate = DateTime.Now, MealType = mt.MealType, PersonOrder = personOrder };context.Set<MealTake>().Add(mealtake);
context.SaveChanges();
想到的解决方法:
Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=8RAN90uJ1967wpt1Y5&redirect_uri=www.xxxx.com%3a8001%2fWxAuthPage.aspx?from=notreserve&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
改成
Response.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=8RAN90uJ1967wpt1Y5&redirect_uri=www.xxxx.com%3a8001%2fWxAuthPage.aspx?from=notreserve&response_type=code&scope=snsapi_base&state="+Guid.NewGuid().ToString()+"#wechat_redirect");
再把插入代码改成
if (!context.Set<PersonOrder>().Any(n => n.Comment == wx.State))
{ var person = context.Set<MealPerson>().Include("PersonType").FirstOrDefault(n => n.Id == wxUserInfo.User.Id); var personOrder = MealOrderService.CreatePersonOrder(person, mt.MealType, mealdate, false); personOrder.Comment = wx.State; var mealtake = new MealTake { Id = Guid.NewGuid(), IsTaked = true, TakeDate = DateTime.Now, MealType = mt.MealType, PersonOrder = personOrder };context.Set<MealTake>().Add(mealtake);
context.SaveChanges(); }=============================================================
具体原因,原来是redirect_uri导致的,漏了对redirect_uri进行完整的UrlEncode:
redirect_uri=www.xxxx.com%3a8001%2fWxAuthPage.aspx?from=notreserve
改成
redirect_uri=www.xxxx.com%3a8001%2fWxAuthPage.aspx%3ffrom%3dnotreserve
就不会发生两次回调了