.net core 增加IP过滤

利用IPAddressRange包实现IP过滤

1、安装nuget上的 IPAddressRange 包

2、继承ActionFilterAttribute

using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
 
namespace ClientIpAspNetCore.Filters
{
    public class ClientIdCheckFilter : ActionFilterAttribute
    {
        private readonly ILogger _logger;
 
        public ClientIdCheckFilter(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger("ClassConsoleLogActionOneFilter");
        }
 
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            _logger.LogInformation($"Remote IpAddress: {context.HttpContext.Connection.RemoteIpAddress}");
 
            // TODO implement some business logic for this...
 
            base.OnActionExecuting(context);
        }
    }
}

3、ActionFilter 可以添加到服务中。

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<ClientIdCheckFilter>();
 
    services.AddMvc();
}

4、作用根据需要专门用于任何控制器

[ServiceFilter(typeof(ClientIdCheckFilter))]
[Route("api/[controller]")]
public class ValuesController : Controller

来自:https://damienbod.com/2016/12/18/implementing-a-client-white-list-using-asp-net-core-middleware/

 

posted @ 2022-01-18 09:57  丁焕轩  阅读(189)  评论(0编辑  收藏  举报