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

如何在ASP.NET Boilerplate React中访问AuditLog数据并实现活跃用户监控?

Hey there! Let's walk through how to access and display your AuditLog data in the ASP.NET Boilerplate React app, plus tackle that active user monitoring question you had.


First: Accessing AuditLog Data (and why your initial attempts didn't work)

ABP actually has built-in support for audit logs, but you don't need to use a generic AsyncCrudAppService or roll a custom OData controller for this. Here's the straightforward approach:

Step 1: Backend Setup (Custom AppService for Audit Logs)

Audit logs are stored in the system via the IAuditLogRepository, so we'll create a dedicated app service to expose the data we need.

First, define a DTO to shape the audit log data for the frontend:

public class AuditLogListDto : EntityDto<long>
{
    public string UserName { get; set; }
    public string ServiceName { get; set; }
    public string MethodName { get; set; }
    public DateTime ExecutionTime { get; set; }
    public int ExecutionDuration { get; set; }
    public string ClientIpAddress { get; set; }
    // Add any other fields you want to display
}

Then create an app service that injects the audit log repository and handles pagination/filtering:

public class AuditLogAppService : ApplicationService, IAuditLogAppService
{
    private readonly IAuditLogRepository _auditLogRepository;

    public AuditLogAppService(IAuditLogRepository auditLogRepository)
    {
        _auditLogRepository = auditLogRepository;
    }

    public async Task<PagedResultDto<AuditLogListDto>> GetListAsync(PagedResultRequestDto input)
    {
        var query = _auditLogRepository.GetAll()
            .OrderByDescending(log => log.ExecutionTime)
            .Select(log => new AuditLogListDto
            {
                Id = log.Id,
                UserName = log.UserName,
                ServiceName = log.ServiceName,
                MethodName = log.MethodName,
                ExecutionTime = log.ExecutionTime,
                ExecutionDuration = log.ExecutionDuration,
                ClientIpAddress = log.ClientIpAddress
            });

        var totalCount = await query.CountAsync();
        var items = await query.PageBy(input).ToListAsync();

        return new PagedResultDto<AuditLogListDto>(totalCount, items);
    }
}

Don't forget to make sure your module has the AuditLoggingModule enabled (it's included by default in most ABP templates, but double-check your module's DependsOn attribute if you run into issues).

Step 2: Frontend Integration (React)

Create a service to call your new backend endpoint:

import { RestService } from '@abp/ng.core';

@Injectable({ providedIn: 'root' })
export class AuditLogService {
  apiName = 'Default';

  getAuditLogs = (input) =>
    this.restService.request(
      {
        method: 'GET',
        url: '/api/app/audit-log',
        params: input,
      },
      { apiName: this.apiName }
    );

  constructor(private restService: RestService) {}
}

Then build a component to fetch and render the logs:

import { useState, useEffect } from 'react';
import { AuditLogService } from './audit-log.service';

const AuditLogTable = () => {
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(true);
  const auditLogService = new AuditLogService();

  useEffect(() => {
    loadLogs();
  }, []);

  const loadLogs = async () => {
    setLoading(true);
    const result = await auditLogService.getAuditLogs({ skipCount: 0, maxResultCount: 20 });
    setLogs(result.items);
    setLoading(false);
  };

  if (loading) return <div>Loading audit logs...</div>;

  return (
    <div className="audit-log-table">
      <h3>Audit History</h3>
      <table>
        <thead>
          <tr>
            <th>User</th>
            <th>Action</th>
            <th>Timestamp</th>
            <th>Duration (ms)</th>
            <th>IP Address</th>
          </tr>
        </thead>
        <tbody>
          {logs.map(log => (
            <tr key={log.id}>
              <td>{log.userName}</td>
              <td>{`${log.serviceName}.${log.methodName}`}</td>
              <td>{new Date(log.executionTime).toLocaleString()}</td>
              <td>{log.executionDuration}</td>
              <td>{log.clientIpAddress}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default AuditLogTable;

Why your initial attempts failed

  • The generic AsyncCrudAppService wasn't ideal because audit logs are system entities with restricted write access (you don't want to expose create/update/delete operations).
  • OData controllers require extra configuration to expose system entities like AuditLog, which is overkill when a simple REST endpoint works better.

Second: Active User Monitoring

You absolutely can implement active user tracking using ABP's built-in tools:

Option 1: Track Recent Activity via Audit Logs

Query audit logs from the last X minutes/hours to get users who've performed actions:

public async Task<List<string>> GetActiveUsersAsync(DateTime since)
{
    return await _auditLogRepository.GetAll()
        .Where(log => log.ExecutionTime >= since && !string.IsNullOrEmpty(log.UserName))
        .Select(log => log.UserName)
        .Distinct()
        .ToListAsync();
}

Expose this via your app service and call it from the frontend to display a list of recently active users.

Option 2: Real-Time Online Users

Use ABP's IOnlineClientManager to get users currently connected to the app:

private readonly IOnlineClientManager _onlineClientManager;

public ActiveUserAppService(IOnlineClientManager onlineClientManager)
{
    _onlineClientManager = onlineClientManager;
}

public List<string> GetCurrentOnlineUsers()
{
    var onlineClients = _onlineClientManager.GetAllClients();
    return onlineClients.Select(client => client.UserName).Distinct().ToList();
}

This gives you a snapshot of users currently logged in and active.


Important Note: Permissions

Make sure to assign the AuditLogging.View permission to the roles that need access to audit logs. You can do this via the ABP Permission Management UI in your app.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:37:38