我正在为使用在 WebApi 5.2.4 上运行的后端服务器的 javascript Web 应用程序进行 selenium 测试(使用 chrome webdriver 在 C# 中编写)。它以非常宽松的设置启用了 CORS:
namespace SealingService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// etc...
}
}
}
通常一切都按预期工作。但是在某些机器上,当服务器由测试脚本启动时,客户端在每次请求时都会遇到 CORS 错误。 chrome 开发控制台显示标准的 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
消息。服务器日志显示 OPTION 请求已到达它,并且它正在发送响应。
当我尝试手动访问任何 API 路由时,服务器返回通用 ASP.NET 404 页面。这让我认为我们的 CORS 配置实际上可以正常工作,但是我们的测试脚本没有正确启动/配置服务器,因此没有注册路由。因此,所有 API 路由都返回 404 页面,这显然没有启用 CORS。
This is the applicationhost.config used by IIS during the tests.这是测试脚本启动服务器的方式:
public static Process StartIIS(string siteName)
{
return Process.Start(@"C:\Program Files (x86)\IIS Express\iisexpress.exe", $"/site:{siteName} /config:{_applicationHostConfigFilePath}");
}
错误只发生在某些机器上,我们无法弄清楚它们之间的配置有何不同。我试过使用 Chrome 的 --disable-web-security
标志,但它似乎没有任何区别。
最佳答案
您通常可以通过更改 web.config 来解决飞行前错误:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
或者通过自定义处理程序中的代码,例如:
if (request.Headers.Contains("Origin") && request.Method.Method == "OPTIONS")
{
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization");
response.Headers.Add("Access-Control-Allow-Methods", "DELETE, POST, PUT, OPTIONS, GET");
}
如果可行,您可以尝试通过例如将 Access-Control-Allow-Origin
更改为您的前端地址。
关于c# - 客户端在 selenium 测试期间无法连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51617153/