我正在尝试获取客户端IP并将值与配置进行比较。如果匹配,则需要返回true / false。如何使此变量可供Web应用程序访问?我是.NET Core的新手。谢谢
我已跟随本文创建中间件类,但不确定如何从此上下文传递变量。
https://docs.microsoft.com/en-us/aspnet/core/security/ip-safelist?view=aspnetcore-2.2
for name, email, message in csv_reader:
yag.send(email, subject = name, contents = message)
print("sent")
time.sleep(wait)
答案 0 :(得分:0)
我会创建一个界面,例如:
public interface IIPChecker
{
bool IsSafe(IPAddress remoteIpAddress);
}
具有实现:
public class IPChecker : IIPChecker
{
private readonly IPAddress[] _safeList;
public IPChecker(string safeList)
{
var _safeList = safeList
.Split(';')
.Select(IPAddress.Parse)
.ToArray();
}
public bool IsSafe(IPAddress remoteIpAddress)
{
return _safeList.Contains(remoteIpAddress);
}
}
并将其注入需要它的控制器中
public class ValuesController : ControllerBase
{
private readonly IIPChecker _ipChecker;
public ValuesController(IIPChecker ipChecker)
{
_ipChecker = ipChecker;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var isValid = _ipChecker.IsSafe(HttpContext.Connection.RemoteIpAddress);
.....
}
}
如果在所有控制器中都需要此信息,则可以将其更改为从类似的东西继承
public class IpCheckController : ControllerBase
{
private readonly IIPChecker _ipChecker;
public IpCheckController(IIPChecker ipChecker)
{
_ipChecker = ipChecker;
}
private bool IsSafe => _ipChecker.IsSafe(HttpContext.Connection.RemoteIpAddress);
}
答案 1 :(得分:0)
获取客户端RemoteIp并与配置值进行比较。您必须先在启动文件中定义 Http访问器,如下所示。
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
,然后在中间件中使用以下代码访问RemoteIp并比较该值。
var remoteIp = context.Request.HttpContext.Connection.RemoteIpAddress.ToString();