如何在CefSharp WPF中设置--allow-file-access-from-files参数
解决CefSharp WPF访问本地文件的CORS限制问题
要让CefSharp WPF允许本地file://协议下的跨域请求,你需要在Cef初始化阶段添加--allow-file-access-from-files命令行参数,而非像独立Chrome那样在启动时传递参数。具体实现步骤如下:
1. 在应用启动时初始化Cef并配置参数
修改App.xaml.cs,重写OnStartup方法,在其中完成Cef的初始化并添加所需参数:
using CefSharp; using CefSharp.Wpf; using System.Windows; namespace Chromium { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { var settings = new CefSettings(); // 添加允许file协议访问本地文件的参数 settings.CefCommandLineArgs.Add("allow-file-access-from-files", "1"); // 确保Cef只初始化一次 if (!Cef.IsInitialized) { Cef.Initialize(settings); } base.OnStartup(e); } protected override void OnExit(ExitEventArgs e) { // 应用退出时释放Cef资源 Cef.Shutdown(); base.OnExit(e); } } }
2. 保留原有界面与加载逻辑(无需修改)
你原有的XAML布局和页面加载代码可以保持不变:
XAML代码
<Window x:Class="Chromium.MainWindow" xmlns:cef="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:Chromium" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Grid> <cef:ChromiumWebBrowser x:Name="browser" IsBrowserInitializedChanged="browser_IsBrowserInitializedChanged"></cef:ChromiumWebBrowser> </Grid> </Window>
C#加载逻辑
private void browser_IsBrowserInitializedChanged(object sender, DependencyPropertyChangedEventArgs e) { browser.LoadUrl("file:///C:/index.html"); }
原理说明
你遇到的CORS错误,是因为Chrome内核(CefSharp基于该内核)默认禁止file://协议下的跨域XMLHttpRequest请求。添加--allow-file-access-from-files参数后,会解除这一限制,效果与你通过Process.Start启动带参数的Chrome完全一致。
注意:务必保证Cef.Initialize仅被调用一次,将其放在应用启动阶段是最优实践。
内容的提问来源于stack exchange,提问作者Frenchy
相关产品推荐
相关产品推荐

