当前位置: 首页 > news >正文

webapi项目添加访问IP限制

第一步:在项目中添加一个cs文件,内容如下,代码中的RemoteEndpointMessageProperty需要引用System.ServiceModel.Channels,如果没有,去NuGet工具箱搜索安装System.ServiceModel.Primitives

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.ServiceModel.Channels;public class IPFilterHandler : DelegatingHandler
{private readonly HashSet<string> _allowedIPs;public IPFilterHandler(){var ips = ConfigurationManager.AppSettings["AllowedIPs"] ?? "";_allowedIPs = new HashSet<string>(ips.Split(','), StringComparer.OrdinalIgnoreCase);}protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){var clientIP = GetClientIp(request);if (_allowedIPs.Contains(clientIP)){return await base.SendAsync(request, cancellationToken);}return request.CreateResponse(HttpStatusCode.Forbidden, new{Code = 403,Message = $"IP {clientIP} 无访问权限"});}private string GetClientIp(HttpRequestMessage request){// 尝试从 X-Forwarded-For 获取(适用于反向代理场景)if (request.Headers.TryGetValues("X-Forwarded-For", out var forwardedFor)){return forwardedFor.First().Split(',').First().Trim();}// 标准方式获取 IPif (request.Properties.ContainsKey("MS_HttpContext")){return ((HttpContextWrapper)request.Properties["MS_HttpContext"]).Request.UserHostAddress;}if (request.Properties.ContainsKey(RemoteEndpointMessageProperty.Name)){var prop = (RemoteEndpointMessageProperty)request.Properties[RemoteEndpointMessageProperty.Name];return prop.Address;}return "0.0.0.0";}
}

第二步:注册,在 WebApiConfig.cs 中,添加

config.MessageHandlers.Add(new IPFilterHandler());

第三步:在Web.config的<appSettings>中添加,value中添加限制的ip,多个用英文逗号隔开

<add key="AllowedIPs" value="10.10.10.1" />

http://www.dtcms.com/a/321950.html

相关文章:

  • 根据字符出现频率排序
  • 【Bellman负环】Cycle Finding
  • (0️⃣基础)程序控制语句(初学者)(第3天)
  • 调用API接口返回参数缺失是什么原因导致的?
  • [3D数据存储] 对象 | OObject | IObject | 属性 | O<类型>Property | I<类型>Property
  • 安全基础DAY2-等级保护
  • linux-文件系统
  • AD8032ARZ-REEL7 ADI亚德诺 运算放大器 集成电路IC
  • 阿拉伯文识别技术:为连接古老智慧与数字未来铺设了关键道路
  • scratch笔记和练习-第11课:穿越峡谷
  • Cell-cultured meat: The new favorite on the future dining table
  • AR眼镜:能源行业设备维护的“安全守护者”
  • Shell脚本实现自动封禁恶意扫描IP
  • 考研复习-计算机组成原理-第四章-指令系统
  • nvm安装低版本的node失败(The system cannot find the file specified)
  • Mysql 如何使用 binlog 日志回滚操作失误的数据
  • 系统构成与 Shell 核心:从零认识操作系统的心脏与外壳
  • 物联网电能表在企业能耗监测系统中的应用
  • 人工智能与交通:出行方式的革新
  • Android 监听task 栈变化
  • 基于R语言,“上百种机器学习模型”学习教程 | Mime包
  • qt qtablewidget自定义表头
  • ubantu20.04 orin nx 显示器驱动
  • 【C++】类和对象--类中6个默认成员函数(2) --运算符重载
  • 【C#】掌握并发利器:深入理解 .NET 中的 Task.WhenAll
  • Docker容器部署前端Vue服务
  • 复杂路况误报率↓78%!陌讯轻量化模型在车辆违停识别的边缘计算优化​
  • 2025-08-08 李沐深度学习11——深度学习计算
  • 位置编码——RoPE篇
  • 机器学习算法篇(七)深入浅出K-means算法:从原理到实战全解析