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

如何实现类Fiddler的HTTP网络监控以捕获MVC网站全部请求?

Got it, let's figure out how to capture all incoming requests to your MVC website—mirroring what Fiddler does, so you'll catch every single request including the main view, JS files, images, and any other assets (like your example: 1 view + 4 JS + 4 images = 9 total requests). Below are practical, server-side approaches tailored to different MVC versions:

Method 1: ASP.NET Core Middleware (.NET Core/.NET 5+)

Middleware is perfect here because it sits in the request pipeline and intercepts every incoming HTTP request—no matter if it's a controller action, a static JS file, or an image. Here's how to implement it:

  1. Create a custom middleware class

    public class RequestCaptureMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<RequestCaptureMiddleware> _logger;
    
        public RequestCaptureMiddleware(RequestDelegate next, ILogger<RequestCaptureMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }
    
        public async Task InvokeAsync(HttpContext context)
        {
            // Capture request details before passing to next middleware
            var requestPath = context.Request.Path.ToString();
            var requestMethod = context.Request.Method;
            var timestamp = DateTime.UtcNow;
    
            _logger.LogInformation($"Captured Request: [{timestamp}] {requestMethod} {requestPath}");
    
            // Continue processing the request
            await _next(context);
        }
    }
    
  2. Register the middleware in your pipeline
    In Program.cs (for .NET 6+):

    var builder = WebApplication.CreateBuilder(args);
    
    // Add MVC services
    builder.Services.AddControllersWithViews();
    builder.Services.AddLogging();
    
    var app = builder.Build();
    
    // Add our request capture middleware BEFORE other middleware (like static files/MVC)
    app.UseMiddleware<RequestCaptureMiddleware>();
    
    app.UseStaticFiles(); // Handles JS, images, etc.
    app.UseRouting();
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    

    Important: Make sure to register your middleware before UseStaticFiles() and UseRouting()—this ensures it catches requests for static assets and controller actions alike.

Method 2: ASP.NET Framework MVC (HttpModule + Action Filter)

In ASP.NET Framework, controller actions are handled separately from static files, so we need two pieces to capture everything:

Part A: HttpModule for Static Assets

This will catch requests for JS, images, CSS, etc.:

public class StaticRequestCaptureModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += OnBeginRequest;
    }

    private void OnBeginRequest(object sender, EventArgs e)
    {
        var app = (HttpApplication)sender;
        var request = app.Context.Request;
        var requestPath = request.FilePath;

        // Check if it's a static asset (adjust extensions as needed)
        var staticExtensions = new[] { ".js", ".png", ".jpg", ".css" };
        if (staticExtensions.Any(ext => requestPath.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
        {
            System.Diagnostics.Debug.WriteLine($"Captured Static Request: {request.HttpMethod} {requestPath}");
        }
    }

    public void Dispose() { }
}

Register it in web.config:

<system.webServer>
  <modules>
    <add name="StaticRequestCaptureModule" type="YourNamespace.StaticRequestCaptureModule" />
  </modules>
</system.webServer>

Part B: Action Filter for Controller Requests

This captures the main view/action requests:

public class RequestCaptureFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var request = filterContext.HttpContext.Request;
        var controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        var action = filterContext.ActionDescriptor.ActionName;

        System.Diagnostics.Debug.WriteLine($"Captured Controller Request: {request.HttpMethod} /{controller}/{action}");
        base.OnActionExecuting(filterContext);
    }
}

Register it globally in Global.asax.cs:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    // Add global action filter
    GlobalFilters.Filters.Add(new RequestCaptureFilter());
}

Verifying the Capture

Once set up, run your MVC app and load the page. Check your logs (for Core) or Debug Output (for Framework)—you should see exactly 9 entries:

  • 1 controller request (the main view)
  • 4 requests for JS files
  • 4 requests for image files

Just like Fiddler, this captures every HTTP request hitting your server—no more missing dependent assets!


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:59:37