.NET Core Web Api 配置ip访问
时间: 2024-01-19 21:05:02 浏览: 196
要配置.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)和错误消息。
阅读全文