我在寻找什么:我正在寻找一种在WPF应用程序中显示包含CSS和JS的本地网页的方法。但是,棘手的是,还应该可以CATCH AND PROCESS外发请求。因此,我需要捕获GetRequest,自己处理它们,然后自己返回答案。
为什么:对于基于服务器的应用程序,我有一个相当广泛的UI。 (HTML / CSS / JS)因此,我可以选择在WPF中完全重新制作整个UI,还是需要找到一种在WPF应用程序中使用基于HTML的UI的方法。尽管显示UI可以与到目前为止我找到的大多数组件一起正常工作,但是捕获请求,然后以JSON格式提供自己的答案似乎是一件棘手的事情。
到目前为止我尝试过的两个:
你们中的任何人都不知道有什么组件/框架可以做到吗?
编辑CefSharp项目:https://1drv.ms/u/s!ArLDiUd-U5dtg06kzBSMOqDZLWxJ?e=Mdkchd
按照我最后得到的解决方案:
JavaScript调用了一个不存在的网页。请求和资源处理程序捕获此调用并返回自己的anwser。当实现自己的请求/资源处理程序时,即使您不需要此功能,在某些情况下也必须替换NotImplementedException。在这种情况下,只需访问官方文档以获取默认行为:http://cefsharp.github.io/api/75.1.x/html/T_CefSharp_IRequestHandler.htm
XAML:
<Window x:Class="Chromium.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
...
xmlns:cefSharp="clr-namespace:CefSharp.Wpf;assembly=CefSharp.Wpf"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<cefSharp:ChromiumWebBrowser
x:Name="ChromiumWebBrowser"
/>
</Grid>
</Window>
MainWindow.Xaml.cs
public MainWindow()
{
InitializeComponent();
ChromiumWebBrowser.BrowserSettings.WebSecurity = CefState.Disabled;
ChromiumWebBrowser.RequestHandler = new RequestHandler();
ChromiumWebBrowser.Address = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestHtml", "index.html");
}
index.html
<!doctype html>
<html>
<head>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script src="js/script.js" type="text/javascript"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<h1>Title</h1>
<p id="result"></p>
<button onclick="call()">Call</button>
</body>
JS脚本
function call() {
axios.get('http://doesnt_exist')
.then((response) => {
console.log(response);
document.getElementById("result").innerHTML = JSON.stringify(response.data);
});
}
请求处理程序
public class RequestHandler : IRequestHandler
{
public IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
{
Console.WriteLine("GetResourceRequestHandler " + request.Url);
return new ResourceRequestHandler();
}
...
}
ResourceRequestHandler
class ResourceRequestHandler : IResourceRequestHandler
{
public IResourceHandler GetResourceHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request)
{
Console.WriteLine("GetResourceHandler " + request.Url);
if (request.Url.Contains("doesnt_exist"))
return ResourceHandler.FromString("Hello");
return null;
}
...
}