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

.NET控制台程序如何获取Initiator为'document'的HttpResponse状态码

解决方案:获取Initiator为'document'的HTTP请求状态码

首先明确:浏览器DevTools中的Initiator=document指的是主文档请求(即打开页面时浏览器发起的第一个请求)。用HttpClient直接请求目标URL本身就对应这个场景,无需Selenium这类重型工具。你的代码问题主要在于逻辑覆盖不全,以及可能未正确触发服务器返回Initiator自定义头。

步骤1:确保请求模拟浏览器主文档行为

部分服务器会根据请求头判断请求来源,只有模拟浏览器请求才会返回Initiator头。添加浏览器UA等请求头:

using (HttpClient client = new HttpClient()) {
    client.DefaultRequestHeaders.Accept.Clear();
    // 添加浏览器User-Agent,模拟主文档请求
    client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
    client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", CredentialsBase64);
    client.Timeout = TimeSpan.FromSeconds(10);
    // ... 后续代码
}

步骤2:修复状态码赋值逻辑

你的当前代码仅在Initiator=document时才设置ReturnCode和Result,导致其他请求的属性为空,看起来“仅能获取最后一个状态码”。调整逻辑,确保每个测试项都有明确结果:

foreach (var test in Tests) {
    try {
        Console.WriteLine($"-> Checking:\n   {test.Name}: {test.URL}");
        HttpResponseMessage response = await client.GetAsync(test.URL);
        test.RunBy = $"{Environment.UserName} ({Environment.MachineName})";

        // 先设置默认结果(处理无Initiator头的情况)
        test.ReturnCode = (int)response.StatusCode;
        test.Result = "Initiator not 'document'";

        string _initiator = response.Headers.TryGetValues("Initiator", out var _initiatorValues) 
            ? _initiatorValues.FirstOrDefault() 
            : null;

        if (_initiator?.Equals("document", StringComparison.OrdinalIgnoreCase) == true) {
            int _code = (int)response.StatusCode;
            test.ReturnCode = _code;

            // 更新为对应结果
            if (_code >= 100 && _code <= 299) {
                test.Result = "Pass";
            } else if (_code >= 300 && _code <= 399) {
                test.Result = "Redirect";
            } else if (_code >= 400 && _code <= 499) {
                test.Result = "Possible fail - client";
            } else if (_code >= 500 && _code <= 599) {
                test.Result = "Fail";
            } else {
                test.Result = "Unknown";
            }
        }
        
        test.Id = _idCntr;
        _idCntr++;
    } catch (TaskCanceledException) {
        test.Result = "Timeout";
        test.ReturnCode = 0; // 给超时项设置明确的状态码标记
        Console.WriteLine($"Timeout for '{test.Name}' ({test.URL})!");
    }
}

步骤3:按需关闭自动重定向(可选)

如果服务器的重定向请求不会返回Initiator=document,而你需要获取初始请求的状态码(而非重定向后的最终响应),可以关闭HttpClient的自动重定向:

var handler = new HttpClientHandler { 
    AllowAutoRedirect = false 
};
using (HttpClient client = new HttpClient(handler)) {
    // 原有请求逻辑
}

关键说明

  • Initiator并非HTTP标准响应头,是目标服务器自定义的字段,需确保你的请求能触发服务器返回该头(通过设置正确的请求头如UA、Referer等)。
  • 上述代码保证每个测试项的ReturnCode和Result都有值,不会出现仅最后一项有结果的情况,同时精准筛选出Initiator=document的请求状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 23:25:55