.Net6 WebApi实现IP访问限制

前言:此功能主要是用来防止一些恶意提交或者防爬机制的一种手段。当然这只是其中一种方式,所谓道高一尺魔高一丈;完全杜绝基本是不现实的。

以下主要还是通过特性来实现,使用起来灵活方便。

efef9fb57e6af6a1d2b44626bbf129b8.png

  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()

f93ad54c4e15b4ac10f15fb38dd2d6f6.png

-

技术群:添加小编微信并备注进群

小编微信:mm1552923   

公众号:dotNet编程大全    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要配置.NET Core Web API允许特定IP地址访问,可以在应用程序启动时添加中间件。以下是一个示例中间件,它将允许特定IP地址的访问。 ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Net; using System.Threading.Tasks; public class IpRestrictionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<IpRestrictionMiddleware> _logger; private readonly string[] _allowedIpAddresses; public IpRestrictionMiddleware(RequestDelegate next, ILogger<IpRestrictionMiddleware> logger, string[] allowedIpAddresses) { _next = next; _logger = logger; _allowedIpAddresses = allowedIpAddresses; } public async Task Invoke(HttpContext context) { var remoteIpAddress = context.Connection.RemoteIpAddress; if (_allowedIpAddresses.Contains(remoteIpAddress.ToString())) { await _next.Invoke(context); } else { _logger.LogWarning($"Request from {remoteIpAddress} rejected."); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; await context.Response.WriteAsync("You are not authorized to access this resource."); } } } public static class IpRestrictionMiddlewareExtensions { public static IApplicationBuilder UseIpRestriction(this IApplicationBuilder builder, string[] allowedIpAddresses) { return builder.UseMiddleware<IpRestrictionMiddleware>(allowedIpAddresses); } } ``` 在`Startup.cs`文件中,可以使用以下代码将中间件添加到管道中: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseIpRestriction(new[] { "127.0.0.1", "::1" }); // add IP addresses to allow // ... } ``` 在上面的示例中,`IpRestrictionMiddleware`类将检查传入请求的远程IP地址,并与允许的IP地址列表进行比较。如果IP地址存在于列表中,则请求将被转发到下一个中间件。否则,请求将被拒绝,并返回HTTP状态码403(Forbidden)和错误消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值