我的 C# 程序如何读取 cefsharp 的 HTTP 响应标头?

问题描述 投票:0回答:2

我现在正在使用 cefsharp 通过 Chrome 浏览器构建程序。在页面加载之前,我想先读取HTTP响应头。对于 HTTP 响应标头,我想获取“Location”的值。 我知道 cefsharp 提供了 IRequestHandler.OnResourceResponse 方法,但响应对象只提供很少的属性。如何获取完整的 http 响应标头或仅读取位置值?谢谢。

cache-control: private
content-length: 132
content-type: text/html
date: Fri, 12 Apr 2019 02:14:05 GMT
location: comeIn.asp
server: Microsoft-IIS/10.0
set-cookie: ASPSESSIONIDSWABBQBT=IDOHGDFDH…DPEIAJFPHIOGJ; secure; path=/
X-Firefox-Spdy: h2
c# httpresponse cefsharp
2个回答
2
投票

假设您想使用回调来处理这些标头,您将将该回调传递给 CefSharp 来处理标头。

首先,您需要声明一个自定义 RequestHandler 来重写该方法

GetResourceRequestHandler
:

using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Specialized;

namespace MachFramework.Windows.Forms.WebBrowser
{
    class HeadersProcessingRequestHandler : RequestHandler
    {
        readonly Func<NameValueCollection, bool> _headersProcessingFunc;
        public HeadersProcessingRequestHandler(Func<NameValueCollection, bool> headersProcessingFunc) => _headersProcessingFunc = headersProcessingFunc;
        protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling) => new HeadersProcessingResourceRequestHandler(_headersProcessingFunc);
    }
}

然后您需要声明此覆盖返回的类,以处理标头:

using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Specialized;

namespace MachFramework.Windows.Forms.WebBrowser
{
    class HeadersProcessingResourceRequestHandler : ResourceRequestHandler
    {
        readonly Func<NameValueCollection, bool> _headersProcessingFunc;
        public HeadersProcessingResourceRequestHandler(Func<NameValueCollection, bool> headersProcessingFunc) => _headersProcessingFunc = headersProcessingFunc;

        protected override bool OnResourceResponse(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            if (_headersProcessingFunc != null)
            {
                return _headersProcessingFunc(response.Headers);
            }
            return false;
        }
    }
 }

最后,您需要将自定义 RequestHandler 分配给您将使用的 CefSharp 浏览器对象:

browser = new ChromiumWebBrowser(url.ToString());
browser.RequestHandler = new HeadersProcessingRequestHandler(headersProcessingFunc);

现在您将能够按照您喜欢的方式处理定义的回调中的标头。回调的 bool 返回可以控制请求的加载是否可以继续:

    /// To allow the resource load to proceed without modification return false. To redirect or retry the resource load optionally
    /// modify <paramref name="request"/> and return true. Modification of the request URL will be treated as a redirect. Requests
    /// handled using the default network loader cannot be redirected in this callback.

0
投票

嗨,我无法实现这个目标

© www.soinside.com 2019 - 2024. All rights reserved.