C#窗体程序内嵌浏览器
前言
👨💻👨🌾📝记录学习成果,以便温故而知新
最近在学习C#窗体程序内嵌浏览器,访问VUE前端。
首先了解了C#窗体程序与VUE放一起,接口单独发布;
然后又了解了C#窗体程序访问VUE项目URL,而VUE项目与接口一起发布
一、VUE项目准备
由于只是一个演示项目,所以只拣重点的记录。
1.新建VUE3项目
vue create test
2.修改项目端口
注意红框中内容
"serve": "vue-cli-service serve --port 8090",
3.修改vue.config.js
注意红框中内容
publicPath:'./',//根路径
作用是修改资源的引用路径
4.项目运行效果:
二、C#窗体内嵌浏览器与VUE放一起
具体细节请看 参考文章
1.新建Windows窗体应用(.NET Framework)
在“工具”菜单打开NuGet包管理器,搜索“CefSharp.WinForms”进行安装,本人安装的是Visual Studio 2017,发现最新的版本安装不了,结果安装的是113.3.5
CefSharp不能在“Any CPU”平台上运行,需要配置“x64”。之前一次是配置到的x86,可能这次的安装的版本变了,所以这也跟着变了。
2.代码
在Windows窗体应用的bin目录下的x64目录下Debug目录下新建vue目录,把VUE项目编译的结果dist目录中内容复制到vue目录
public partial class Form1 : Form
{
ChromiumWebBrowser browser;
public void InitBrowser()
{
CefSettings settings = new CefSettings();
// Note that if you get an error or a white screen, you may be doing something wrong !
// Try to load a local file that you're sure that exists and give the complete path instead to test
// for example, replace page with a direct path instead :
//String url = "http://www.html5test.com";//有用的浏览器测试页
String url = AppDomain.CurrentDomain.BaseDirectory + @"vue/index.html";
// Initialize cef with the provided settings
Cef.Initialize(settings);
// Create a browser component
browser = new ChromiumWebBrowser(url);
// Add it to the form and fill it to the form window.
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
// Allow the use of local resources in the browser
BrowserSettings browserSettings = new BrowserSettings();
//browserSettings.FileAccessFromFileUrls = CefState.Enabled;//报错,注释
//browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;//报错,注释
browser.BrowserSettings = browserSettings;
}
public Form1()
{
InitializeComponent();
InitBrowser();
}
}
3.效果
如图
VUE项目的资源引入一定要设置正确,否则可能有问题。
三、VUE项目与接口一起发布
Windows窗体应用只须把
String url = "http://www.html5test.com";//有用的浏览器测试页
这行代码改成VUE项目的访问地址,就可以了,所以不做过多说明。
接口分两种情况
1.ASP.NET Web应用程序(.NET Framework)
新建ASP.NET Web应用程序(.NET Framework),把VUE项目编译的结果dist目录中内容复制到项目根目录。
目录结构如图:
修改HomeController,代码如下
public class HomeController : Controller
{
public ActionResult Index()
{
//ViewBag.Title = "Home Page";
Server.Transfer(Url.Content("~/index.html"));
//return View();
return new EmptyResult();
}
}
运行效果
2.ASP.NET Core Web应用程序
ASP.NET Core Web应用程序需要安装上图红框中的工具,否则无法建立项目。
新建ASP.NET Core Web应用程序,把VUE项目编译的结果dist目录中内容复制到项wwwroot目录中。
目录结构如图:
修改Startup类Configure函数中添加如下代码:
// 防止刷新页面报404
app.Run(async (context) =>
{
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
});
这代码暂时没有发现有什么明显作用。
运行效果如图:
VUE效果: