The general SMS interface, or the paid interface, needs to be limited to the number of calls within a certain period of time.
This article mainly based on client IP to make a distinction between the number of calls, only consider the possibility of a level of proxy.
First, we get the client IP based on the following two lines of code
string ipaddress = "";//Get real IP
if ((httpcontext.current.request.servervariables["http_x_forwarded_for"]!= null
&& httpcontext.current.request.servervariables["Http_x_forwarded_for"]!= String.Empty))
{
IPAddress = httpcontext.current.request.servervariables["Http_x_forwarded_for"];
}
Else
{
ipaddress= httpcontext.current.request.servervariables["REMOTE_ADDR"];
}
The following functions are then invoked to verify the resulting IP
<summary>
Limit the number of API interface calls
</summary>
<param name= "Key" ></param>
<returns></returns>
public static bool Checkcount (string key)
{
TimeSpan const_rediskeyexpiryhours = new TimeSpan (1, 0, 0, 0);/cache cycle
String con = "Jituan:Robotapi:count";//General prefix
The using (var redisclient = Waterredisclient.getwaterclientmanager ())//Object pool gets a Redis client
{
if (!string. IsNullOrEmpty ((String) redisClient.Redis.GetDatabase (). Stringget (con + key+ "BLACK"))
{
return false; Blacklist check
}
var tempkey = con + DateTime.Now.Hour + "_" + key;
var reslut =redisclient.redis.getdatabase (). Stringget (Tempkey);
if (Reslut. IsNull)
{
RedisClient.Redis.GetDatabase (). Stringset (Tempkey, 1, const_rediskeyexpiryhours);
return true;
}
Else
{
var count = Convert.ToInt32 (Reslut);
if (count<20)//20 no interference, no inspection
{
RedisClient.Redis.GetDatabase (). Stringincrement (Tempkey);
return true;
}
Else
{
Double survivaltime = RedisClient.Redis.GetDatabase (). Keytimetolive (Tempkey). value.totalseconds;//remaining surviving time
Double dietime = * * 60-survivaltime;//number of seconds elapsed
Double limitcount = number of times per second limit 0.8;//
Double Limitmax = dietime * LIMITCOUNT;
if (limitmax< count)
{
RedisClient.Redis.GetDatabase (). Stringset (Con + "_black" + key, 1, const_rediskeyexpiryhours);
return false;
}
RedisClient.Redis.GetDatabase (). Stringincrement (Tempkey);
return true;
}
}
}
}