反爬是不太现实的 只能防一下低端爬虫,
public class AccessLogMiddleWare
{
private readonly RequestDelegate _next;
public AccessLogMiddleWare(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, ILogger<AccessLogMiddleWare> logger, AppDbContext db)
{
// 切割请求地址
var type = context.Request.Path.ToString().Split('.').Last();
if (type == "html")
{
logger.LogInformation(context.Request.Path + "\t" + context.Connection.RemoteIpAddress.MapToIPv4().ToString() + "\t" + context.Request.Headers["X-Real-IP"] + "\t" + context.Request.Headers["X-Forwarded-For"] + "\t" + context.Request.Headers["Referer"]);
//if (context.Connection.RemoteIpAddress.MapToIPv4().ToString() != "0.0.0.1") { }
var log = new AccessLog
{
AccessTime = DateTime.Now,
Ip = string.IsNullOrEmpty(context.Request.Headers["X-Real-IP"].ToString()) ? context.Connection.RemoteIpAddress.MapToIPv4().ToString() : context.Request.Headers["X-Real-IP"].ToString(),
ForwardIp = string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"].ToString()) ? context.Connection.RemoteIpAddress.MapToIPv4().ToString() : context.Request.Headers["X-Forwarded-For"].ToString(),
Referer = context.Request.Headers["Referer"].ToString(),
Url = context.Request.Path.ToString()
};
db.Add(log);
await db.SaveChangesAsync();
}
await _next(context);
}
}
public static class AccessLogMiddleWareExtensions
{
public static IApplicationBuilder AccessLogMiddleWare(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AccessLogMiddleWare>();
}
}