我尝试使用 playwright 将 Post 命令发送到 Rest API, 它不会等到页面重定向到 json 响应并返回 js 挑战页面(如 cloudflare)作为结果,该页面无法转换为 json 并引发异常。
private IPlaywright _playwright;
private IBrowser _browser;
private IBrowserContext _context;
public async Task InitializePlaywrightAsync()
{
_playwright = await Playwright.CreateAsync();
_browser = await _playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = true });
_context = await _browser.NewContextAsync();
}
private async Task<JObject?> PostToUrlAsJObject(string url, StringContent content)
{
try
{
string con = await content.ReadAsStringAsync();
var response = await _context.APIRequest.PostAsync(url, new()
{
DataString = con,
Headers = new Dictionary<string, string>
{
{ "Content-Type", "application/json" },
{ "Accept", "application/json" },
{ "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" },
{ "Referer", url },
{ "Origin", new Uri(url).GetLeftPart(UriPartial.Authority) },
{ "Accept-Language", "en-US,en;q=0.9" },
{ "Accept-Encoding", "gzip, deflate, br" }
},
});
string res = await response.TextAsync();
return JObject.Parse(res);
}
catch (Exception ex)
{
Console.WriteLine($"Error during POST request:\r\nURL: {url}\r\nError: {ex.Message}\r\nStack Trace: {ex.StackTrace}");
return null;
}
}
还没有看到类似的 C# 问题...
您无需启动浏览器即可使用 c# 在 Playwright 中进行 API 测试
如官方链接中所述您可以使用它来获取请求上下文
private IAPIRequestContext Request = null!;
然后调用API
Request = await this.Playwright.APIRequest.NewContextAsync(new() {
// All requests we send go to this API endpoint.
BaseURL = "https://api.github.com",
});
var newIssue = await Request.PostAsync("/repos/" + USER + "/" + REPO + "/issues", new() { DataObject = data });
如果您只想测试 Post API,请删除该浏览器代码