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

如何在ASP.NET网页中创建类网络调试控制台的调试窗口

在ASP.NET网页中实现内置调试控制台区域

核心思路

通过后端收集API调用日志,前端渲染一个可交互的控制台区域,仅在开发环境显示,用于查看接口请求详情、状态码及响应内容。


1. 后端日志收集实现

创建线程安全的静态日志管理器,存储API调用记录:

using System.Collections.Concurrent;
using System.Net;

public static class DebugLogger
{
    private static readonly ConcurrentQueue<DebugLogEntry> _logEntries = new();

    public static void LogApiCall(string endpoint, HttpMethod method, int statusCode, string responseContent)
    {
        _logEntries.Enqueue(new DebugLogEntry
        {
            Endpoint = endpoint,
            Method = method.Method,
            StatusCode = statusCode,
            ResponseContent = responseContent,
            Timestamp = DateTime.Now
        });
    }

    public static List<DebugLogEntry> GetAllLogs() => _logEntries.ToList();

    public static void ClearLogs()
    {
        while (_logEntries.TryDequeue(out _)) { }
    }
}

public class DebugLogEntry
{
    public string Endpoint { get; set; }
    public string Method { get; set; }
    public int StatusCode { get; set; }
    public string ResponseContent { get; set; }
    public DateTime Timestamp { get; set; }
}

在API调用处添加日志记录(以HttpClient为例):

var httpClient = new HttpClient();
var response = await httpClient.GetAsync("/api/weatherforecast");
var responseContent = await response.Content.ReadAsStringAsync();

// 记录API调用日志
DebugLogger.LogApiCall("/api/weatherforecast", HttpMethod.Get, (int)response.StatusCode, responseContent);

2. 调试接口控制器

添加控制器用于前端获取和清空日志:

using Microsoft.AspNetCore.Mvc;

public class DebugController : Controller
{
    [HttpGet("/Debug/GetLogs")]
    public IActionResult GetLogs()
    {
        return Json(DebugLogger.GetAllLogs());
    }

    [HttpPost("/Debug/ClearLogs")]
    public IActionResult ClearLogs()
    {
        DebugLogger.ClearLogs();
        return Ok();
    }
}

3. 前端控制台UI实现

在页面中添加调试区域(仅在开发环境渲染):

@using Microsoft.AspNetCore.Hosting
@inject IWebHostEnvironment Env

@if (Env.IsDevelopment())
{
    <div class="debug-console">
        <div class="console-header">
            <h3>API调试控制台</h3>
            <div>
                <button id="clearLogsBtn" class="btn btn-sm btn-secondary">清空日志</button>
                <button id="toggleConsoleBtn" class="btn btn-sm btn-primary ms-2">折叠/展开</button>
            </div>
        </div>
        <div class="console-body" id="consoleBody">
            <table class="table table-sm table-striped">
                <thead>
                    <tr>
                        <th>时间</th>
                        <th>请求方法</th>
                        <th>接口地址</th>
                        <th>状态码</th>
                        <th>响应内容</th>
                    </tr>
                </thead>
                <tbody id="logTableBody"></tbody>
            </table>
        </div>
    </div>

    <style>
        .debug-console {
            margin: 2rem;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            background-color: #f8f9fa;
        }

        .console-header {
            padding: 0.8rem;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .console-body {
            padding: 1rem;
            max-height: 450px;
            overflow-y: auto;
        }

        .log-row.success {
            background-color: #d1e7dd;
        }

        .log-row.error {
            background-color: #f8d7da;
        }

        pre {
            white-space: pre-wrap;
            word-wrap: break-word;
            margin: 0;
            font-size: 0.9rem;
        }
    </style>

    <script>
        window.addEventListener('load', () => {
            loadLogs();
            
            // 清空日志
            document.getElementById('clearLogsBtn').addEventListener('click', async () => {
                const response = await fetch('/Debug/ClearLogs', { method: 'POST' });
                if (response.ok) {
                    document.getElementById('logTableBody').innerHTML = '';
                }
            });
            
            // 折叠/展开
            document.getElementById('toggleConsoleBtn').addEventListener('click', () => {
                const body = document.getElementById('consoleBody');
                body.style.display = body.style.display === 'none' ? 'block' : 'none';
            });
        });

        async function loadLogs() {
            const response = await fetch('/Debug/GetLogs');
            const logs = await response.json();
            const tableBody = document.getElementById('logTableBody');
            
            tableBody.innerHTML = logs.map(log => {
                const rowClass = log.StatusCode >= 200 && log.StatusCode < 300 ? 'log-row success' : 'log-row error';
                return `
                    <tr class="${rowClass}">
                        <td>${new Date(log.Timestamp).toLocaleString()}</td>
                        <td>${log.Method}</td>
                        <td>${log.Endpoint}</td>
                        <td>${log.StatusCode}</td>
                        <td><pre>${log.ResponseContent}</pre></td>
                    </tr>
                `;
            }).join('');
        }
    </script>
}

4. 额外优化方向

  • 实时刷新:集成SignalR推送新日志,无需手动刷新页面
  • 筛选功能:按状态码、请求方法过滤日志条目
  • 日志导出:添加按钮将日志导出为JSON文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:40:18