WebUI3中的WebView2:如何禁用CORS以获取请求?
我有一个简单的Web应用程序,我想在Winui应用程序中运行,该应用程序可以获取外部HTML内容:
private async fetchHtml() {
const url = document.querySelector<HTMLInputElement>("#txt-url")!.value;
const html = await fetch(url).then(r => r.text());
document.querySelector<HTMLTextAreaElement>("#txt-html")!.value = html;
}
显然,这会遇到CORS错误。我想禁用它,但找不到winui3的任何方法:
-
this Answer 无济于事。
-
The URL is external URL so
SetVirtualHostNameToFolderMapping
suggested by -
我尝试注入自己的CORS标头,但它在
fetch
上不起作用(webresourceresponsereceived
事件仅在fetch
请求上不触发事件):
c.WebResourceResponseReceived += (_, e) =>
{
var origin = e.Request.Headers.FirstOrDefault(q => q.Key == "Origin").Value;
if (!string.IsNullOrEmpty(origin))
{
e.Response.Headers.AppendHeader("Access-Control-Allow-Origin",
new Uri(e.Request.Uri).GetLeftPart(UriPartial.Authority));
e.Response.Headers.AppendHeader("Access-Control-Allow-Methods", "*");
e.Response.Headers.AppendHeader("Access-Control-Allow-Headers", "*");
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,事实证明,您实际上需要在
Webresourcerequested
事件中处理代理请求。webresourceresponsereceived
是在浏览器处理请求之后触发。要手动代理请求,您需要首先设置a Web资源请求的过滤器。
然后,您可以像
webresourceresponsereceived
一样设置侦听器,因此要代理请求,您需要设置 httpclient 并手动处理请求。
例如,这将代表所有请求,假设
httpclient
定义为httpclient
:注意
在构建响应对象时,请勿使用
async
方法。 COM层不尊重线程。So it turns out you actually need to handle proxying the request in the
WebResourceRequested
event.WebResourceResponseReceived
is triggered after the browser handles the request.To proxy the request manually, you need to first set up a web resource requested filter.
Then you can set up a listener just like for
WebResourceResponseReceived
So to proxy the request, you need to set up an HttpClient and handle the requests manually.
For example, this will proxy all requests, assuming
httpClient
is defined as anHttpClient
:NOTE
Should not use
async
methods when building out a response object. The COM layer does not respect threading.