You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Asp.net MVC中基于数据库实现博客浏览量统计功能

ASP.NET MVC 博客浏览量统计实现方案

一、数据库设计(两种可选方案)

方案1:直接扩展博客表(简单快速)

在现有Blog表中新增ViewCount字段,用于存储累计浏览量,类型设为INT,默认值0。

SQL示例:

ALTER TABLE Blog ADD ViewCount INT DEFAULT 0 NOT NULL;

方案2:独立浏览日志表(支持精细化统计)

如果需要记录访问者IP、访问时间等细节,便于后续做访问趋势分析,新增BlogViewLog表:

CREATE TABLE BlogViewLog (
    Id INT PRIMARY KEY IDENTITY(1,1),
    BlogId INT FOREIGN KEY REFERENCES Blog(Id),
    VisitorIp NVARCHAR(50) NOT NULL,
    VisitTime DATETIME DEFAULT GETDATE() NOT NULL
);

这种方案通过统计BlogId对应的记录数得到浏览量,同时保留了访问明细。

二、数据访问层(EF示例)

假设使用Entity Framework,先更新实体类:

对应方案1的实体修改

public class Blog
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    // 新增浏览量字段
    public int ViewCount { get; set; }
    // 其他原有字段...
}

对应方案2的实体新增

public class BlogViewLog
{
    public int Id { get; set; }
    public int BlogId { get; set; }
    public string VisitorIp { get; set; }
    public DateTime VisitTime { get; set; }

    public Blog Blog { get; set; }
}

在数据仓储类(如BlogRepository)中实现操作方法:

方案1:更新与获取浏览量

public void IncrementViewCount(int blogId)
{
    var blog = _dbContext.Blogs.Find(blogId);
    if (blog != null)
    {
        blog.ViewCount++;
        _dbContext.SaveChanges();
    }
}

public int GetViewCount(int blogId)
{
    var blog = _dbContext.Blogs.Find(blogId);
    return blog?.ViewCount ?? 0;
}

方案2:添加日志与统计浏览量

public void AddViewLog(int blogId, string visitorIp)
{
    var log = new BlogViewLog
    {
        BlogId = blogId,
        VisitorIp = visitorIp,
        VisitTime = DateTime.Now
    };
    _dbContext.BlogViewLogs.Add(log);
    _dbContext.SaveChanges();
}

public int GetViewCount(int blogId)
{
    return _dbContext.BlogViewLogs.Count(l => l.BlogId == blogId);
}

三、避免重复计数的逻辑

为防止同一用户短时间内重复刷新导致计数虚高,可通过Cookie标记已访问:

在博客详情页的Action中:

public ActionResult Details(int id)
{
    var blog = _blogRepository.GetById(id);
    if (blog == null)
    {
        return HttpNotFound();
    }

    var cookieKey = $"BlogVisited_{id}";
    if (Request.Cookies[cookieKey] == null)
    {
        // 方案1:更新Blog表的ViewCount
        _blogRepository.IncrementViewCount(id);
        // 方案2:添加浏览日志(需获取访客IP)
        // var visitorIp = Request.UserHostAddress;
        // _blogRepository.AddViewLog(id, visitorIp);

        // 设置Cookie,有效期1天(可按需调整)
        Response.Cookies.Add(new HttpCookie(cookieKey)
        {
            Expires = DateTime.Now.AddDays(1),
            HttpOnly = true
        });
    }

    ViewBag.ViewCount = _blogRepository.GetViewCount(id);
    return View(blog);
}

四、视图层展示

博客详情页显示浏览量

在Details.cshtml的合适位置添加:

<div class="blog-meta">
    <span>浏览量:@ViewBag.ViewCount</span>
</div>

后台管理面板展示统计

在后台博客列表页面中添加浏览量列:

<table class="admin-blog-list">
    <thead>
        <tr>
            <th>标题</th>
            <th>浏览量</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var blog in Model)
        {
            <tr>
                <td>@blog.Title</td>
                <td>@blog.ViewCount</td> <!-- 方案1直接取字段 -->
                <!-- 方案2需提前查询每个博客的浏览量并传入Model -->
                <td><a href="@Url.Action("Edit", "Blog", new { id = blog.Id })">编辑</a></td>
            </tr>
        }
    </tbody>
</table>

五、最佳实践

  • 异步更新:使用SaveChangesAsync()异步方法,或借助Hangfire等工具将浏览量更新放入后台任务,避免阻塞页面响应。
  • 缓存优化:将高访问量博客的浏览量存入Redis或MemoryCache,定时同步到数据库,减少数据库请求次数。
  • 独立访客统计:若需精准统计独立访客,可在BlogViewLog表中按BlogId和VisitorIp去重,统计时用COUNT(DISTINCT VisitorIp)。
  • 数据备份:定期备份浏览日志数据,防止数据丢失。

内容的提问来源于stack exchange,提问作者Abhishek Deshmukh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 21:53:17