Or How to inject a custom header into the initial request to a site when new-ing up an instance of the ChromiumWebBrowser.
I'm a noob with Chromium and could really use some help. I have a winforms app with a CEF window. K, no prob so far. What I need to do is to call/load the initial url with a custom http-header that contains authentication info. Is this possible?
The following is essentially what is at play and all parts work except the custom header (Doh!)
Winform(CEF httpRequest(with custom header)) [never gets past this point]=> C# MVC web app => Owin_Authentication_Pipeline segment => MVC Response with populated Razor view => Shows up in Winform Chromium app.
Maybe this will help as well:
using CefSharp;
using CefSharp.WinForms;
...
private void Form1_Load(object sender, EventArgs e)
{
Cef.Initialize();
ChromiumWebBrowser myBrowser = new ChromiumWebBrowser("whatever.com");
// ??How do i get a custom header be sent with the above line??
myBrowser.Dock = DockStyle.Fill;
//myBrowser.ShowDevTools();
//myBrowser.RequestHandler = new DSRequestHander();
//myBrowser.FrameLoadStart += myBrowser_FrameLoadStart;
this.Controls.Add(myBrowser);
}
I Groggled this to death, looked, tried all the tricks in my toolbox and then some.
Any ideas, help or hints on how I might be able to solve or get around this boggler is greatly appreciated. Thanks in advance.
Updated to reflect major Chromium changes
Updated to reflect changes made in version 75
(should work in 75
and newer)
The method you're after should be OnBeforeResourceLoad
, a basic example should look like:
public class CustomResourceRequestHandler : ResourceRequestHandler
{
protected override CefReturnValue OnBeforeResourceLoad(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
var headers = request.Headers;
headers["User-Agent"] = "My User Agent";
request.Headers = headers;
return CefReturnValue.Continue;
}
}
public class CustomRequestHandler : RequestHandler
{
protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
{
return new CustomResourceRequestHandler();
}
}
browser.RequestHandler = new CustomRequestHandler();
Using the IRequest.Headers
property you must read the headers property, make changes then reassign it. It's now possible to use the SetHeaderByName/GetHeaderByName
functions to get/set a single header.