惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
D
Docker
GbyAI
GbyAI
Y
Y Combinator Blog
Google DeepMind News
Google DeepMind News
G
Google Developers Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Stack Overflow Blog
Stack Overflow Blog
WordPress大学
WordPress大学
小众软件
小众软件
Engineering at Meta
Engineering at Meta
酷 壳 – CoolShell
酷 壳 – CoolShell
I
InfoQ
B
Blog
H
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 聂微东
The GitHub Blog
The GitHub Blog
A
About on SuperTechFans
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog

博客园 - 火冰·瓶

Cloudflare Tunnel 有两种模式 用 Cloudflare Tunnel 实现从外网 SSH 登录内网服务器 Cloudflare + .NET Core MVC 部署完整流程 net core 后端获取网络图片的扩展名 推荐好用的web控件 ubuntu运维 使用Frp+Caddy把https映射到内网的web服务 net core中结合EntityFrameworkCore的DB first使用PostgreSQL OneDrive中设置不同步某个文件夹 Framework 4.7老项目运行到caddy Action<T> 和 Func<T>的用法 EF Core经验 net core随记 asp.net core 记录页面访问记录 asp.net core 发布到caddy asp.net core发布到Caddy获取用户的真实ip 统计文章阅读量,一小时内重复刷新的不重复统计 使用on()方法绑定事件,解决动态加载的元素事件绑定 鼠标悬停在图片上方时,显示文字
asp.net core 记录页面访问次数,同一个IP一个小时只算一次
火冰·瓶 · 2025-04-02 · via 博客园 - 火冰·瓶

1.访问记录服务

 public class PageVisitService
 {
     private readonly IMemoryCache _memoryCache;
     private readonly TimeSpan _timeSpan = TimeSpan.FromHours(1);

     public PageVisitService(IMemoryCache memoryCache)
     {
         _memoryCache = memoryCache;
     }

     public bool RegisterVisit(string ipAddress)
     {
         string cacheKey = $"PageVisit_{ipAddress}";

         if (_memoryCache.TryGetValue(cacheKey, out _))
         {
             return false; // 该 IP 在过去一小时已记录,不计数
         }

         _memoryCache.Set(cacheKey, true, _timeSpan);
         return true; // 记录新的访问
     }
 }

2.在 Program.csStartup.cs 添加:

builder.Services.AddMemoryCache();
builder.Services.AddSingleton<PageVisitService>();

3.在控制器中调用

public class VisitController : ControllerBase
{
    private readonly PageVisitService _pageVisitService;

    public VisitController(PageVisitService pageVisitService)
    {
        _pageVisitService = pageVisitService;
    }

    [HttpGet]
    public IActionResult Visit()
    {
       string userIp = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "Unknown";

       if (_pageVisitService.RegisterVisit(userIp))
       {
           //保存数据库,持久化操作
           //recruitInfo.VisitTimes++;
           //recruitDAL.UpdateRecruitInfo(recruitInfo);
           //await _mySqlTrainDbContext.SaveChangesAsync();
       }
    }
}