欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

CefSharp過濾圖片RequestHandler問題

 更新時間:2023年01月16日 09:28:07   作者:MC-DEV  
這篇文章主要介紹了CefSharp過濾圖片RequestHandler問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

C# CefSharp 過濾 RequestHandler 圖片

1、方式一

ChromiumWebBrowser 實現(xiàn) IRequestHandler

具體內(nèi)同參照 附錄;將 OnBeforeResourceLoad方法替換成2中的內(nèi)容,很簡單;

2、方式二

繼承集成默認的抽象類 DefaultRequestHandler

?internal class RequestHandler : DefaultRequestHandler?
? ? {

? ? ? ? public ?override CefReturnValue ?OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
? ? ? ? {

? ? ? ? ? ? if (request.ResourceType == ResourceType.Image)
? ? ? ? ? ? ? ? return CefReturnValue.Cancel;

? ? ? ? ? ? return CefReturnValue.Continue;
? ? ? ? }
}

對比實現(xiàn)接口方式和繼承集成默認的抽象類,發(fā)現(xiàn)抽象類可以只實現(xiàn)相關(guān)的處理方法更加靈活。而若采用IRequestHandler需要實現(xiàn)RequestHandler接口中的所有方法,否則拋出未實現(xiàn)異常;

和其他網(wǎng)上從Response環(huán)節(jié)過濾資源圖片的方法不同,這里談到的方法在請求圖片資源之前,可以節(jié)省流量,加快頁面訪問速度等。

附錄:

using System;
using CefSharp.Example.Filters;
using System.Security.Cryptography.X509Certificates;
using System.Collections.Generic;
using System.Text;
using CefSharp.Handler;

namespace CefSharp.Example.Handlers
{
    /// <summary>
    /// DefaultRequestHandler provides a base class for you to inherit from 
    /// you only need to implement the methods that are relevant to you. 
    /// If you implement the IRequestHandler interface you will need to
    /// implement every method
    /// </summary>
    public class RequestHandler : IRequsetHandler
    {
        public static readonly string VersionNumberString = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}",
            Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion);

        private Dictionary<UInt64, MemoryStreamResponseFilter> responseDictionary = new Dictionary<UInt64, MemoryStreamResponseFilter>();

        public override bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool userGesture, bool isRedirect)
        {
            return false;
        }

        public override bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
        {
            return false;
        }

        public override bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    //To allow certificate
                    //callback.Continue(true);
                    //return true;
                }
            }

            return false;
        }

        public override void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
        {
            // TODO: Add your own code here for handling scenarios where a plugin crashed, for one reason or another.
        }

        public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
        {
            Uri url;
            if (Uri.TryCreate(request.Url, UriKind.Absolute, out url) == false)
            {
                //If we're unable to parse the Uri then cancel the request
                // avoid throwing any exceptions here as we're being called by unmanaged code
                return CefReturnValue.Cancel;
            }

            //Example of how to set Referer
            // Same should work when setting any header

            // For this example only set Referer when using our custom scheme
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                //Referrer is now set using it's own method (was previously set in headers before)
                request.SetReferrer("http://google.com", ReferrerPolicy.Default);
            }

            //Example of setting User-Agent in every request.
            //var headers = request.Headers;

            //var userAgent = headers["User-Agent"];
            //headers["User-Agent"] = userAgent + " CefSharp";

            //request.Headers = headers;

            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    if (request.Method == "POST")
                    {
                        using (var postData = request.PostData)
                        {
                            if(postData != null)
                            { 
                                var elements = postData.Elements;

                                var charSet = request.GetCharSet();

                                foreach (var element in elements)
                                {
                                    if (element.Type == PostDataElementType.Bytes)
                                    {
                                        var body = element.GetBody(charSet);
                                    }
                                }
                            }
                        }
                    }

                    //Note to Redirect simply set the request Url
                    //if (request.Url.StartsWith("https://www.google.com", StringComparison.OrdinalIgnoreCase))
                    //{
                    //    request.Url = "https://github.com/";
                    //}

                    //Callback in async fashion
                    //callback.Continue(true);
                    //return CefReturnValue.ContinueAsync;
                }
            }

            return CefReturnValue.Continue;
        }

        public override bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.

            callback.Dispose();
            return false;
        }

        public override bool OnSelectClientCertificate(IWebBrowser browserControl, IBrowser browser, bool isProxy, string host, int port, X509Certificate2Collection certificates, ISelectClientCertificateCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            callback.Dispose();
            return false;
        }

        public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
        {
            // TODO: Add your own code here for handling scenarios where the Render Process terminated for one reason or another.
            browserControl.Load(CefExample.RenderProcessCrashedUrl);
        }

        public override bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
        {
            //NOTE: If you do not wish to implement this method returning false is the default behaviour
            // We also suggest you explicitly Dispose of the callback as it wraps an unmanaged resource.
            //callback.Dispose();
            //return false;

            //NOTE: When executing the callback in an async fashion need to check to see if it's disposed
            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    //Accept Request to raise Quota
                    //callback.Continue(true);
                    //return true;
                }
            }

            return false;
        }

        public override void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, ref string newUrl)
        {
            //Example of how to redirect - need to check `newUrl` in the second pass
            //if (request.Url.StartsWith("https://www.google.com", StringComparison.OrdinalIgnoreCase) && !newUrl.Contains("github"))
            //{
            //    newUrl = "https://github.com";
            //}
        }

        public override bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
        {
            return url.StartsWith("mailto");
        }

        public override void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
        {

        }

        public override bool OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            //NOTE: You cannot modify the response, only the request
            // You can now access the headers
            //var headers = response.Headers;

            return false;
        }

        public override IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
        {
            var url = new Uri(request.Url);
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                if(request.Url.Equals(CefExample.ResponseFilterTestUrl, StringComparison.OrdinalIgnoreCase))
                {
                    return new FindReplaceResponseFilter("REPLACE_THIS_STRING", "This is the replaced string!");
                }

                if (request.Url.Equals("custom://cefsharp/assets/js/jquery.js", StringComparison.OrdinalIgnoreCase))
                {
                    return new AppendResponseFilter(System.Environment.NewLine + "http://CefSharp Appended this comment.");
                }

                //Only called for our customScheme
                var dataFilter = new MemoryStreamResponseFilter();
                responseDictionary.Add(request.Identifier, dataFilter);
                return dataFilter;
            }

            //return new PassThruResponseFilter();
            return null;
        }

        public override void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
        {
            var url = new Uri(request.Url);
            if (url.Scheme == CefSharpSchemeHandlerFactory.SchemeName)
            {
                MemoryStreamResponseFilter filter;
                if(responseDictionary.TryGetValue(request.Identifier, out filter))
                {
                    //TODO: Do something with the data here
                    var data = filter.Data;
                    var dataLength = filter.Data.Length;
                    //NOTE: You may need to use a different encoding depending on the request
                    var dataAsUtf8String = Encoding.UTF8.GetString(data);                
                }
            }
        }
    }
}

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 簡單實現(xiàn)C#窗體程序判斷是否閏年

    簡單實現(xiàn)C#窗體程序判斷是否閏年

    這篇文章主要介紹了簡單實現(xiàn)C#窗體程序判斷是否閏年的相關(guān)代碼,禁止窗體調(diào)整大小,關(guān)閉窗體前的判斷,感興趣的小伙伴們可以參考一下
    2016-07-07
  • C#泛型方法在lua中表示的一種設(shè)計詳解

    C#泛型方法在lua中表示的一種設(shè)計詳解

    這篇文章主要給大家介紹了關(guān)于C#泛型方法在lua中表示的一種設(shè)計的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2019-03-03
  • c#讀取excel內(nèi)容內(nèi)容示例分享

    c#讀取excel內(nèi)容內(nèi)容示例分享

    這篇文章主要介紹了c#讀取excel內(nèi)容內(nèi)容示例,要求Excel需是.xls格式,需要的朋友可以參考下
    2014-03-03
  • Unity快速生成常用文件夾的方法

    Unity快速生成常用文件夾的方法

    這篇文章主要介紹了Unity快速生成常用文件夾的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-09-09
  • DevExpress實現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法

    DevExpress實現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法

    這篇文章主要介紹了DevExpress實現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法,需要的朋友可以參考下
    2014-08-08
  • C#獲取文件夾下所有的文件

    C#獲取文件夾下所有的文件

    這篇文章主要為大家詳細介紹了C#中獲取文件夾下所有的文件的多種方法,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2024-10-10
  • 關(guān)于C#?dynamic裝箱問題

    關(guān)于C#?dynamic裝箱問題

    裝箱是將值類型轉(zhuǎn)換為類型對象或此值類型實現(xiàn)的任何接口類型的過程,裝箱和拆箱的概念是 C# 類型系統(tǒng)統(tǒng)一視圖的基礎(chǔ),其中任何類型的值都可以視為對象,這篇文章主要介紹了關(guān)于C#?dynamic裝箱引發(fā)的思考,需要的朋友可以參考下
    2022-05-05
  • Unity3D基于OnGUI實時顯示FPS

    Unity3D基于OnGUI實時顯示FPS

    這篇文章主要介紹了Unity3D基于OnGUI實時顯示FPS,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-11-11
  • C#實現(xiàn)俄羅斯方塊

    C#實現(xiàn)俄羅斯方塊

    這篇文章主要為大家詳細介紹了C#實現(xiàn)俄羅斯方塊小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-11-11
  • c# 免費組件html轉(zhuǎn)pdf的實現(xiàn)過程

    c# 免費組件html轉(zhuǎn)pdf的實現(xiàn)過程

    這篇文章主要介紹了c# 免費組件html轉(zhuǎn)pdf的實現(xiàn)過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06

最新評論