.Net6 WebApi实现IP访问限制

前言:此功能主要是用来防止一些恶意提交或者防爬机制的一种手段。当然这只是其中一种方式,所谓道高一尺魔高一丈;完全杜绝基本是不现实的。
以下主要还是通过特性来实现,使用起来灵活方便。.
  1. 新建一个类继承自ActionFilterAttribute,并实现以下构造函数

 
public class IPAttribute : ActionFilterAttribute {
readonly int _max; /// <summary> /// IP限制 /// </summary> /// <param name="max">IP最大可访问数</param> public IPAttribute(int max) { _max = max; }
  1. OnActionExecuting方法中实现以下代码
     public override void OnActionExecuting(ActionExecutingContext context)        {            string ip = context.HttpContext.Connection.RemoteIpAddress.ToString();            ICacheService cacheService =AppSettings.GetService(typeof(ICacheService)) as ICacheService;            int count = 0;            if (cacheService.Exists(ip))            {                count = (int)cacheService.Get(ip);                if (count >= _max)                {                    LogUtil.Warn(ip);                    context.Result = new ApiJsonResult(ApiResult.Error, "今日提交次数已达上限!");                }                else                {                    cacheService.Add(ip, ++count);                }            }            else            {                cacheService.Add(ip, ++count, new TimeSpan(1, 0, 0, 0));            }            base.OnActionExecuting(context);        }
  1. 以上就实现了对IP次数的基本限制,但是由于目前代理IP的廉价性,所以我们需要进一步扩展下,以下是我通过GPT得到的获取真实IP的代码,真实性还未验证;另外就是,即便此代码生效,那也是可以防的住一些廉价的IP,对于高质量的IP依然获取不到。
    public string GetClientIpAddress(HttpContext context){    string ipAddress = context.Connection.RemoteIpAddress.ToString();    if (context.Request.Headers.ContainsKey("X-Forwarded-For"))    {        // Use the first IP address from the X-Forwarded-For header        string[] forwardedIps = context.Request.Headers["X-Forwarded-For"].ToString().Split(',');        ipAddress = forwardedIps.FirstOrDefault()?.Trim();    }    return ipAddress;}
  1. 调用,在需要控制的Action或者Controller上加上即可

 
[IP(2)]public ApiJsonResult Index()