C# 重播存储在文本文件中的 Web 请求

C# Replay web request stored in text file

我有许多 Web 请求存储在文本文件中,我想重播到 Web 应用程序。是否可以使用 C# 自动执行此操作,而不必先解析每个请求以提取 headers 和内容等,然后重建请求?

例如,我是否可以将以下内容加载到字节数组(或类似的东西)中,如果也将主机设置为连接,则将其作为 Web 请求发送?

GET / HTTP/1.1
Host: google.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close

一般情况下,您可以使用IHttpContextAccessor

获取详细信息

您可以为此使用依赖注入。

下面的示例代码,您需要根据自己的需要修改使用:

using APOC.Backend.Framework.Interfaces;
using Microsoft.AspNetCore.Http;
using System;
using System.Security.Claims;

namespace APOC.Backend.Framework.Custom
{
    public class ContextAccessService : IContextAccessService
    {
        private readonly IHttpContextAccessor _context;
        public ContextAccessService(IHttpContextAccessor context)
        {
            _context = context;
        }

        public Guid GetId()
        {
            string userId = _context.HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (userId == null)
            {
                userId = Guid.Empty.ToString();
            }

            return new Guid(userId);
        }


        public string GetIp()
        {
            var x = _context.HttpContext?.Connection?.RemoteIpAddress?.ToString();
            return x;
        }

    }
}

你可以试试

public static void Test(string filename)
{
    // Use string[] readFromFile = File.ReadAllLines(filename) to get the following array
    string[] readFromFile = new string[7];
    readFromFile[0] = "GET / HTTP/1.1";
    readFromFile[1] = "Host: google.com";
    readFromFile[2] = "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0";
    readFromFile[3] = "Accept: */*";
    readFromFile[4] = "Accept-Language: en-US,en;q=0.5";
    readFromFile[5] = "Accept-Encoding: gzip, deflate";
    readFromFile[6] = "Connection: close";
    string url = "";
    string requestType = "";
    string requestProto = "";
    HttpClientHandler clientHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate };
    HttpClient client = new HttpClient(clientHandler);
    foreach (string param in readFromFile)
    {
        if(param.ToUpper().StartsWith("GET") || param.ToUpper().StartsWith("POST"))  // add more commands here
        {
            requestType = param.ToUpper().Substring(0, param.IndexOf(" "));
            requestProto = param.ToUpper().Substring(param.IndexOf(" "), param.Length - param.IndexOf(" ")).ToUpper();
            if (requestProto.Contains("HTTPS"))
                requestProto = "https://";
            else
                requestProto = "http://";
        }
        if(param.Contains(": "))
        {
            string key = param.Substring(0, param.IndexOf(":")).Trim();
            string value = param.Substring(param.IndexOf(":") + 1, param.Length - (param.IndexOf(":") + 1)).Trim();
            if (param.ToLower().StartsWith("host:"))
            {
                url = value;
            }
            else
            {
                client.DefaultRequestHeaders.Add(key, value);
            }
        }
    }
    if (!string.IsNullOrWhiteSpace(requestProto) && !string.IsNullOrWhiteSpace(requestType) && !string.IsNullOrWhiteSpace(url))
    {
        url = requestProto + url;
        // Don't need the .GetAwaiter().GetResult() in an async function
        HttpResponseMessage resp = null;
        switch (requestType)
        {
            case "GET":
                resp = client.GetAsync(url).GetAwaiter().GetResult();
                break;
            case "POST":
                resp = client.PostAsync(url, null).GetAwaiter().GetResult();
                break;

        }
                
        string content = resp.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        Console.WriteLine(content);
    }
}

示例位于 https://rextester.com/LOJ37914