背景

在浏览器中访问本地静态资源html网页时,可能会遇到跨域问题如图。

是因为浏览器默认启用了同源策略,即只允许加载与当前网页具有相同源(协议、域名和端口)的内容。

WebView2默认情况下启用了浏览器的同源策略,即只允许加载与主机相同源的内容。所以如果我们把静态资源发布到iis或者通过node进行启动就可以看到不跨域了。

解决方案

  1. 使用CORS(Cross-Origin Resource Sharing):如果你有控制服务器端,可以在服务器端配置CORS来允许跨域请求。在服务器端的响应头中添加相关的CORS头部信息,例如允许访问的域名、请求方法等,以允许JavaScript跨域访问。

  2. 使用WebView2的 AddWebResourceRequestedFilter 方法:通过添加Web资源请求过滤器,你可以拦截WebView2控件中加载的资源请求,并进行处理。在拦截到JavaScript文件请求时,修改响应头部信息,添加Access-Control-Allow-Origin头部来解决跨域问题。
  3. 使用代理服务器:你可以在本地启动一个代理服务器,将WebView2控件的请求转发到代理服务器上,然后代理服务器再将请求发送到原始服务器并返回响应。在代理服务器上你可以设置合适的CORS头部信息来解决跨域问题。

思路

  1. 首先,确保你已经安装了Microsoft.Web.WebView2。你可以在Visual Studio的NuGet包管理器中搜索并安装此包。

  2. 然后通过HttpListener进行文件夹的静态资源进行代理发布
  3. 然后通过webview2进行导航访问即可我们会发现跨域问题已经解决

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace WinApp.View
{
public partial class Cors : Form
{
// 创建HttpListener对象并指定绑定的端口
HttpListener _listener;
string _folderPath;
string _rootDirectory; public Cors()
{
InitializeComponent(); // 初始化
InitializeAsync();
} private async void InitializeAsync()
{
// 获取本地静态资源的路径
_rootDirectory = AppDomain.CurrentDomain.BaseDirectory + "offline-exam-player"; //设置本地离线播放器为代理服务
_rootDirectory = @"C:\Users\admin\Documents\WeChat Files\wxid_1ofgk575ybpt22\FileStorage\File\2024-02\ng-alain8\ng-alain8/";
_folderPath = @"C:\Users\admin\Documents\WeChat Files\wxid_1ofgk575ybpt22\FileStorage\File\2024-02\ng-alain8\ng-alain8/index.html"; _listener = new HttpListener();
// 设置代理服务器的监听地址和端口号
_listener.Prefixes.Add("http://localhost:8080/");
_listener.Start(); // 启动代理服务器
Task.Run(() =>
{
// 启动代理服务器
ProcessRequests();
}); // 停止代理服务器(这里演示就不停止了)
//server.Stop();
} private void ProcessRequests()
{
try
{
while (_listener.IsListening)
{
HttpListenerContext context = _listener.GetContext();
string requestPath = context.Request.Url.AbsolutePath;
string filePath = _rootDirectory + requestPath; // Serve the requested file if it exists
if (System.IO.File.Exists(filePath))
{
string extension = System.IO.Path.GetExtension(filePath);
string contentType;
switch (extension)
{
case ".html":
contentType = "text/html";
break;
case ".js":
contentType = "application/javascript";
break;
case ".less":
case ".css":
contentType = "text/css";
break;
case ".svg":
contentType = "image/svg+xml";
break;
default:
contentType = "application/octet-stream";
break;
} context.Response.ContentType = contentType;
//context.Response.ContentType = "text/html";
byte[] responseBuffer = System.IO.File.ReadAllBytes(filePath);
context.Response.OutputStream.Write(responseBuffer, 0, responseBuffer.Length);
context.Response.Close();
}
else
{
// Return a 404 response if the file does not exist
context.Response.StatusCode = 404;
context.Response.Close();
}
}
}
catch (Exception ex)
{
// Handle any exceptions that may occur
Console.WriteLine(ex.ToString());
}
} private async void Cors_Load(object sender, EventArgs e)
{
//本地静态资源,直接访问会出现跨院,如果通过iis访问则不会跨域; // 确保CoreWebView2运行时已准备就绪
await webView21.EnsureCoreWebView2Async(); // 在WebView2控件中加载URL
//webView21.CoreWebView2.Navigate(_folderPath);
webView21.CoreWebView2.Navigate("http://localhost:8080/" + "index.html");
} }
}

代理服务帮助类代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks; namespace WinApp.Until
{
public class ProxyHelper
{
private readonly HttpListener _listener;
private readonly string _rootDirectory; /// <summary>
/// 实例化
/// </summary>
/// <param name="serviceIp">代理的ip地址带端口,例子:http://localhost:8080/ </param>
/// <param name="folderPath">需要代理的文件夹,例子:AppDomain.CurrentDomain.BaseDirectory + "offline-exam-player" </param>
public ProxyHelper(string serviceIp, string folderPath)
{
_rootDirectory = folderPath; _listener = new HttpListener();
_listener.Prefixes.Add(serviceIp);
} public async Task Start()
{
_listener.Start(); await Task.Run(() => ProcessRequests()); } public void Stop()
{
_listener.Stop();
_listener.Close();
Console.WriteLine("Proxy server stopped.");
} private void ProcessRequests()
{
try
{
while (_listener.IsListening)
{
HttpListenerContext context = _listener.GetContext();
string requestPath = context.Request.Url.AbsolutePath;
string filePath = _rootDirectory + requestPath; // Serve the requested file if it exists
if (System.IO.File.Exists(filePath))
{
string extension = System.IO.Path.GetExtension(filePath);
string contentType;
switch (extension)
{
case ".html":
contentType = "text/html";
break;
case ".js":
contentType = "application/javascript";
break;
case ".less":
case ".css":
contentType = "text/css";
break;
case ".svg":
contentType = "image/svg+xml";
break;
default:
contentType = "application/octet-stream";
break;
} context.Response.ContentType = contentType;
//context.Response.ContentType = "text/html";
byte[] responseBuffer = System.IO.File.ReadAllBytes(filePath);
context.Response.OutputStream.Write(responseBuffer, 0, responseBuffer.Length);
context.Response.Close();
}
else
{
// Return a 404 response if the file does not exist
context.Response.StatusCode = 404;
context.Response.Close();
}
}
}
catch (Exception ex)
{
// Handle any exceptions that may occur
Console.WriteLine(ex.ToString());
}
}
}
}

结语

最后如果对于不多的跨域js文件,可以把js的代码内嵌到index.html页面实现。就是<script>跨域js内容</script>

c#使用webView2 访问本地静态html资源跨域Cors问题 (附带代理服务helper帮助类)的更多相关文章

  1. 访问本地json文件因跨域导致的问题

    我使用jquery的getJSON的方法获取本地的json文件,并进行操作,获取json 数据代码如下: $.getJSON("invite_panel.json",functio ...

  2. vue-cli 项目优化之3种方法对比:本地静态库资源(推荐)、cdn、DllPlugin

    vue-cli 项目优化之3种方法对比:本地静态库资源(推荐).cdn.DllPlugin 事项 本地静态库资源 cdn DllPlugin 依赖 依赖cdn网站资源(有种完善方法:如果cdn引入不成 ...

  3. nginx/apache静态资源跨域访问问题详解

    1. apache静态资源跨域访问 找到apache配置文件httpd.conf 找到这行 #LoadModule headers_module modules/mod_headers.so把#注释符 ...

  4. IIS Manager 配置文件修该,允许跨域CORS访问

    IIS Manager 配置文件修该,允许跨域CORS访问 IIS Manager 的api访问会出现跨域问题,需要 IIS Manager的配置文件中修改. 配置文件的路径:C:\Program F ...

  5. nginx配置访问本地静态资源

    下面说说如何在windows下使用nginx作为静态资源服务器, 1.修改config目录下,这个配置文件,基本上所有的配置都在这里面做, 2.主要的配置参数如下,一些无关的参数我直接去掉了,注意,里 ...

  6. linux服务器上如何使用nginx访问本地静态资源

    查看80端口是否被占用,一般80端口多被apache服务占用. netstat -anp|grep 80 2.修改apache服务的端口号 vim /etc/apache2/ports.conf 3. ...

  7. URL资源跨域访问 跨域使用session信息

    SilverLight 出于对安全性的考虑默认情况下对URL的访问进行了严格的限制,只允许访问同一子域下的URL资源. 下表列出了Silverlight 2.0 中 URL 访问规则:   WebCl ...

  8. Nginx解决前端访问资源跨域问题

    被前端跨域问题折磨快2天后,终于用ngnx的方式解决了,所以在此总结下. 该篇只探讨如何用Ngnx解决跨域问题,对于原理不作讨论. 1.首先介绍Windows环境下Nignx的相关命令操作 nginx ...

  9. nodejs服务实现反向代理,解决本地开发接口请求跨域问题

    前后端分离项目需要解决第一个问题就是,前端本地开发时如何解决通过ajax请求产生的跨域的问题.一般的做法是通过本地配置nginx反向代理进行处理的,除此之外,还可以通过nodejs来进行代理接口.当然 ...

  10. html文件引用本地js文件出现跨域问题的解决方案

    在本地做个小demo,很简单,一个html文件,一个js文件,在html文件中通过<script>标签引入js,但是出现了一个意想不到的问题:浏览器报错—— 一番折腾后,终于弄明白了:加载 ...

随机推荐

  1. 登录chatgpt的时候出现429的解决方法,亲测有效

    登录chatgpt的时候出现429的解决方法 PS:在2023年3月14日晚还是可以用的,亲测有效 登录chatgpt的时候出现429的解决方法 很多时候在国内用代理进入chatgpt的时候会出现42 ...

  2. 力扣442(java)-数组中重复的数据(中等)

    题目: 给你一个长度为 n 的整数数组 nums ,其中 nums 的所有整数都在范围 [1, n] 内,且每个整数出现 一次 或 两次 .请你找出所有出现 两次 的整数,并以数组形式返回. 你必须设 ...

  3. 力扣430(java)-扁平化多级双向链表(中等)

    题目: 你会得到一个双链表,其中包含的节点有一个下一个指针.一个前一个指针和一个额外的 子指针 .这个子指针可能指向一个单独的双向链表,也包含这些特殊的节点.这些子列表可以有一个或多个自己的子列表,以 ...

  4. 为 Serverless Devs 插上 Terraform 的翅膀,解耦代码和基础设施,实现企业级多环境部署(下)

    简介: 在上篇<为 Serverless Devs 插上 Terraform 的翅膀,实现企业级多环境部署(上)>中,主要介绍了 Serverless Devs 多环境功能的使用,用户读完 ...

  5. 阿里巴巴在 Envoy Gateway 的演进历程浅析

    ​简介:最近阅读 <Envoy Gateway 来了>这篇文章,深感 Envoy 强大的可扩展性和基于 Envoy Gateway 带来的易用性,在 K8s 架构下,Envoy 重新定义了 ...

  6. CDN应用进阶 | 正确使用CDN 让你更好规避安全风险

    为了帮助用户更好地了解和使用CDN产品,CDN应用实践进阶系统课程开课了.12月17日,阿里云CDN产品专家彭飞在线分享了<正确使用CDN,让你更好规避安全风险>议题,内容主要包括以下几个 ...

  7. Flink on Zeppelin 流计算处理最佳实践

    简介: 欢迎钉钉扫描文章底部二维码进入 EMR Studio 用户交流群 直接和讲师交流讨论~ 点击以下链接直接观看直播回放:https://developer.aliyun.com/live/247 ...

  8. 技术干货 | 闲鱼:一个优秀的 Push 平台,需要经历怎样的前世今生

    ​简介: mPaaS 消息推送服务,快速集成多家厂商 Push 通道,有效提高用户留存率,提升用户体验. 编者荐语: 点击这里,了解 mPaaS 消息推送服务,快速集成多家厂商 Push 通道,有效提 ...

  9. [Cryptocurrency] (XMR) Monero GUI 连接远程节点 操作方式

    Monero 官网下载的钱包,在 高级设置 的节点里支持 "本地节点" 和 "远程节点". 本地节点就是同步区块链数据到本地电脑,安全性高,占用空间大. 远程节 ...

  10. OpenTK 入门 初始化窗口

    本文属于 OpenTK 入门博客,这是一项使用 C# 做底层调用 OpenGL 和 OpenAL 和 OpenCL 的技术.但值得一提的是,如果是想做渲染相关的话,当前是不建议使用 OpenGL 的, ...