两种微信缓存方式(7200s)
第一种是MemoryCache(缓存的分享票据)
public static string Getjsapi_ticket(string AppID, string AppSecret)
{
string tt = "";
string ticket = AddOrGetExisting<string>("ticket", delegate()
{
string strUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
WebResponse response = request.GetResponse();
Stream resStream = response.GetResponseStream();
StreamReader sr = new StreamReader(resStream);
string result = sr.ReadToEnd();
string regex = ""access_token":"(?<token>.*?)"";
Match mt = Regex.Match(result, regex);
string token = "";
if (mt.Success)
{
token = mt.Groups["token"].Value;
}
string jsapi_url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", token);
HttpWebRequest jsapi_request = (HttpWebRequest)WebRequest.Create(jsapi_url);
WebResponse jsapi_response = jsapi_request.GetResponse();
Stream jsapi_resStream = jsapi_response.GetResponseStream();
StreamReader jsapi_sr = new StreamReader(jsapi_resStream);
string jsapi_result = jsapi_sr.ReadToEnd();
string temp = jsapi_result.Split(',')[2];
string jsapi_tic = temp.Split(':')[1];
jsapi_tic = jsapi_tic.Substring(1, jsapi_tic.Length - 2);
return jsapi_tic;
},
new TimeSpan(0, 0, 7000)//7000秒过期
);
return ticket;
}
static readonly ObjectCache cache = MemoryCache.Default;
public static T AddOrGetExisting<T>(string key, Func<T> createNew, TimeSpan cacheDuration)
{
return AddOrGetExisting<T>(key, new TimeSpan(0, 0, 7000), createNew);
}
public static T AddOrGetExisting<T>(string key, TimeSpan cacheDuration, Func<T> createNew)
{
if (key == null) throw new ArgumentNullException("key");
if (createNew == null) throw new ArgumentNullException("createNew");
if (!cache.Contains(key))
{
cache.Add(key, createNew(), DateTime.Now.Add(cacheDuration));
}
return (T)cache[key];
}
第二种HttpContext.Current.Cache(缓存的access_token)
/// <summary>
/// 获取公众号的ACCESS_TOKEN
/// </summary>
/// <returns>返回操作凭据</returns>
public string GetAccessToken()
{
if (HttpContext.Current.Cache["access_token"] == null)
{
string para = string.Format("grant_type=client_credential&appid={0}&secret={1}", AppID, AppSecret);
string results = SendHTTPRequest("POST", "https://api.weixin.qq.com/cgi-bin/token", para);
JObject obj = (JObject)JsonConvert.DeserializeObject(results);
//设置access_token的过期
Cache cache = HttpContext.Current.Cache;
cache.Insert("access_token", obj["access_token"].ToString(), null, DateTime.Now.AddSeconds(7000),
System.Web.Caching.Cache.NoSlidingExpiration);
return HttpContext.Current.Cache["access_token"].ToString();
}
else
{
return HttpContext.Current.Cache["access_token"].ToString();
}
}