.net简单的限流过滤器
|
freeflydom
2024年6月13日 8:42
本文热度 1844
|
API接口都是提供给第三方服务/客户端调用,所有请求地址以及请求参数都是暴露给用户的。
每次请求一个HTTP请求,用户都可以通过F12,或者抓包工具看到请求的URL链接,然后copy出来。这样是非常不安全的,有人可能会恶意的刷我们的接口,那这时该怎么办呢?
增加一个全局过滤器 获取客户端的IP 限制固定时间内的访问次数即可
第一步:创建全局过滤器 RateLimitFilter
public class RateLimitFilter : ActionFilterAttribute
{
private const int MaxRequests = 30;
private bool StartUp = true;
public override void OnActionExecuting(ActionExecutingContext context)
{
if (StartUp)
{
base.OnActionExecuting(context);
string clientId = GetIP();
if (GetCache(clientId) == null)
{
SetCacheRelativeTime(clientId, 1, 60);
}
else
{
var cs = int.Parse(GetCache(clientId).ToString());
SetCacheRelativeTime(clientId, cs += 1, 60);
}
if (int.Parse(GetCache(clientId).ToString()) > MaxRequests)
{
context.Result = new ContentResult { Content = "<script type='text/javascript'>alert('" + clientId + " 访问过于频繁,请稍等片刻!');</script><h1 style='text-align: center; color: red;'>" + clientId + " 访问过于频繁,请稍等片刻!<h1>" };
}
}
}
public static string GetIP()
{
string userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
}
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = HttpContext.Current.Request.UserHostAddress;
}
if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
{
return userHostAddress;
}
return "127.0.0.1";
}
public static bool IsIP(string ip)
{
return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
#region 设置相对过期时间Cache值(即:访问激活后不过期)
public static void SetCacheRelativeTime(string objectkey, object objObject, int timeSpan)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
objCache.Insert(objectkey, objObject, null, DateTime.MaxValue, TimeSpan.FromSeconds(timeSpan));
}
#endregion
#region 获取当前应用程序指定CacheKey的Cache值
public static object GetCache(string CacheKey)
{
try
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
Object value = objCache[CacheKey];
if (value != null)
{
return value;
}
else
{
return null;
}
}
catch (Exception)
{
return null;
}
}
#endregion
}
第二步:FilterConfig
类并注册你的全局过滤器
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new RateLimitFilter());
}
}
第三步:Global.asax 文件中注册全局过滤器
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
UnityConfig.RegisterComponents();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
原文链接https://www.cnblogs.com/zj19940610/p/18244414 作者:风中起舞
该文章在 2024/6/13 8:42:45 编辑过