.Net 核心分析

.Net Core Analytics

进入.net core的站点,我需要记录人的IP地址,他浏览了哪个页面,每天有多少人登录等状态,并显示在管理面板中。我研究了这个主题,遇到了一个叫做 IActionFilter 的东西,但我不知道该怎么做,你能帮我解决这个问题吗?

只需在 Google 中快速搜索,您就可以找到一些很棒的预先设计的解决方案(即 google 分析)

您可以开发自己的服务器端分析日志存储

例如:

https://www.codeproject.com/Articles/1251484/Introducing-Server-Side-Analytics-for-ASP-NET-Core

另一个更好、更具可扩展性的解决方案是将 ELK 堆栈添加到您的项目中, 然后你就可以查询你的应用程序数据并向客户展示你想要的任何内容。

这个问题有很多解决方案,您应该自己研究哪种解决方案最适合您的需求。

您遇到了正确的概念,即 IActionFilter 可以帮助您实现目标。

现在让我们一一进入你的问题。

此人IP地址:

你可以通过local IPRemote IP两种方式获取,那怎么获取呢?那么我们开始吧

 var remoteIP = context.HttpContext.Connection.RemoteIpAddress;
 var localIP = context.HttpContext.Connection.LocalIpAddress;

他浏览了哪个页面:

对于 asp.net core 方面的这种情况,我们可以通过 controlleraction 来考虑所有事情,对吗?我的意思是我们在 asp.net 核心生命周期内所做的任何事情,除了在特定的 controller 中的 controlleraction 我们在一起吗?

如果是这样,那么如果我们可以获得 controlleraction 信息,那么您的问题就解决了。那么现在的问题是如何?这是解决方案

var request = context.HttpContext.Request;
var currentUser = context.HttpContext.User.Identity.Name;
string controller = context.RouteData.Values["controller"].ToString();
string actions = context.RouteData.Values["action"].ToString();

每天登录人数:

所以现在,一旦用户登录到您的系统,您就有登录信息了吗?所以算上它写一些 LinqSQL 然后 order by perticular date 然后你可以很容易地得到它:例如:

SELECT 
COUNT(*) TotalUserLoggedIn,
login_date

FROM user_log 
GROUP BY login_date
ORDER BY login_date

输出:

应用程序 DbContext:

您的应用程序数据库应该喜欢这样将用户记录保存到数据库中。在这种情况下,它就像:

public class MvcAttendanceDbContext: DbContext
    {
        public MvcAttendanceDbContext(DbContextOptions<MvcAttendanceDbContext> options) : base(options)
        {
        }
        public DbSet<UserLog> UserLogs { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
           
            modelBuilder.Entity<UserLog>().ToTable("UserLog");
           
        }

        internal object Query<T>(string v, string name, int employeeId)
        {
            throw new NotImplementedException();
        }
    }

appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=YourSQLServerName;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "AllowedHosts": "*"
}

在 Startup.cs 上注册数据库上下文:

您应该在 Startup.cs

下的 ConfigureService 中注册此服务
         services.AddDbContext<MvcAttendanceDbContext>(options =>
         options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

现在谈谈你的观点...

但是我不知道该怎么做:

好吧,伙计,别担心,我会告诉你细节实现

LogAnalyticsActionFilter:

public class LogAnalyticsActionFilter : IActionFilter
    {
        
        public void OnActionExecuting(ActionExecutingContext context)
        {
        
           
            var user = context.HttpContext.User.Claims;
            var remoteIP = context.HttpContext.Connection.RemoteIpAddress;
            var localIP = context.HttpContext.Connection.LocalIpAddress;
            //Get Your Page Information
            var request = context.HttpContext.Request;
            var currentUser = context.HttpContext.User.Identity.Name;
            string controller = context.RouteData.Values["controller"].ToString();
            string action = context.RouteData.Values["action"].ToString();
            var httpVerb = context.HttpContext.Request.Method;

            //Database Operation Context
            var _dbContext = context.HttpContext.RequestServices.GetRequiredService<MvcAttendanceDbContext>();
            //User Log Object
            var userLog = new UserLog();
            userLog.user_id = "", // Get your Login your Id Here
            userLog.user_name = currentUser
            userLog.login_date = DateTime.Now;
            userLog.login_time = DateTime.Now.ToString("HH:mm:ss tt");
            userLog.ip_address = localIP.ToString();
            userLog.page_name = action;
            userLog.controller = controller;
            userLog.http_verb = httpVerb;
            //Save the context
            _dbContext.UserLogs.Add(userLog);
            _dbContext.SaveChanges();
            Debug.Write(MethodBase.GetCurrentMethod(), context.HttpContext.Request.Path);
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
           
            var user = context.HttpContext.User.Claims;
            var remoteIP = context.HttpContext.Connection.RemoteIpAddress;
            var localIP = context.HttpContext.Connection.LocalIpAddress;
          
            //Get Your Page Information
            var request = context.HttpContext.Request;
            var currentUser = context.HttpContext.User.Identity.Name;
            string controller = context.RouteData.Values["controller"].ToString();
            string action = context.RouteData.Values["action"].ToString();
            var httpVerb = context.HttpContext.Request.Method;

            //Database Operation Context
            var _dbContext = context.HttpContext.RequestServices.GetRequiredService<MvcAttendanceDbContext>();
            //User Log Object
            var userLog = new UserLog();
            userLog.user_id = "", // Get your Login your Id Here
            userLog.user_name = currentUser
            userLog.login_date = DateTime.Now;
            userLog.login_time = DateTime.Now.ToString("HH:mm:ss tt");
            userLog.ip_address = localIP.ToString();
            userLog.page_name = action;
            userLog.controller = controller;
            userLog.http_verb = httpVerb;
            //Save the context
            _dbContext.UserLogs.Add(userLog);
            _dbContext.SaveChanges();

            Debug.Write(MethodBase.GetCurrentMethod(), context.HttpContext.Request.Path);
        }
        
    }

Startup.cs:

只需在 startup.cs 文件中注册上述 actionFilter,如下所示:

services.AddMvc(config =>
    {
       config.Filters.Add(new LogAnalyticsActionFilter());
    });

用户日志模型:

public class UserLog
    {
        [Key]
        public long ulogo_id { get; set; }
        public long user_id { get; set; }
        [Required]
        public string user_name { get; set; }
        public DateTime login_date { get; set; }
        public string login_time { get; set; }
        public string ip_address { get; set; }
        public string page_name { get; set; }
        public string controller { get; set; }
        public string http_verb { get; set; }
       
    }

用户日志控制器:

public class UserLogController : Controller
    {
        private readonly MvcAttendanceDbContext _context;

        public UserLogController(MvcAttendanceDbContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
        
            var userLog = _context.UserLogs.ToList();
            
            return View(userLog);
        }
    }

用户日志查看:

@model IEnumerable<MVCApps.Models.UserLog>

@{
    ViewData["Title"] = "Index";
}

<h2>User Log</h2>
<table class="table">
    <thead>
        <tr>
            <th>Date</th>
            <th>Total User</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>@DateTime.Now.ToShortDateString()</th>
            <th>@Model.Count()</th>
        </tr>
    </tbody>
</table>
<hr />

    <table class="table">
        <thead>
            <tr>
               
                <th>
                  User Id
                </th>
                <th>
                   User Name
                </th>
                <th>
                   Login Date
                </th>
                <th>
                  Time
                </th>
                <th>
                   IP Address
                </th>
                <th>
                  Page Visited
                </th>
                <th>
                  Controller Name
                </th>
                <th>
                   Action Performed
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                  
                    <td>
                        @Html.DisplayFor(modelItem => item.user_id)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.user_name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.login_date)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.login_time)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ip_address)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.page_name)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.controller)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.http_verb)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                    </td>
                </tr>
            }
        </tbody>
    </table>

最终输出:

Note: If you would like to take time more about IActionFilter you could have a look our official document here

希望对您有所帮助。

Update: Here is the github link of this project. To run the project please change the database connection string on app.settings file. After that run the script on your database DatabaseScript.txt which you can get on data folder or you can add migration command. then build the project and run.