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

推荐订阅源

博客园 - 三生石上(FineUI控件)
博客园 - 叶小钗
博客园 - 聂微东
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Recent Announcements
Recent Announcements
IT之家
IT之家
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
爱范儿
爱范儿
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
博客园 - Franky
U
Unit 42
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
F
Fortinet All Blogs
V
Visual Studio 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();
       }
    }
}