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

推荐订阅源

Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
小众软件
小众软件
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
Hugging Face - Blog
Hugging Face - Blog
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
量子位
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
云风的 BLOG
云风的 BLOG
M
MIT News - Artificial intelligence
F
Fortinet All Blogs
T
Tailwind CSS Blog
Martin Fowler
Martin Fowler
I
InfoQ
The GitHub Blog
The GitHub Blog
有赞技术团队
有赞技术团队
The Cloudflare 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();
       }
    }
}