Пример #1
0
        /// <summary>
        /// Send a POST request to the specified <see cref="Uri"/> and return the response body
        /// as a string in an asynchronous operation.
        /// </summary>
        /// <param name="requestUri">The <see cref="Uri"/> the request is sent to.</param>
        /// <param name="content">The request content sent to the specified <see cref="Uri"/>.</param>
        /// <param name="cancellationToken">
        /// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public async Task <string> PostReadStringAsync(Uri requestUri, IEnumerable <KeyValuePair <string, string> > content, CancellationToken cancellationToken)
        {
            var request = await PostAsync(requestUri, content, cancellationToken).ConfigureAwait(false);

            AssertSuccess(request);

            Stream responseStream = request.GetResponseStream();

            if (responseStream is null)
            {
                return(string.Empty);
            }

            CefResponse response = request.Response;

            if (response is null)
            {
                return(null);
            }

            Encoding encoding;

            try
            {
                encoding = Encoding.GetEncoding(response.Charset);
            }
            catch (ArgumentException)
            {
                encoding = this.DefaultEncoding;
            }
            return(new StreamReader(responseStream, encoding).ReadToEnd());
        }
Пример #2
0
 protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
 {
     response.Status     = 200;
     response.StatusText = "OK";
     responseLength      = 0;
     redirectUrl         = null;
 }
Пример #3
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string?redirectUrl)
        {
            redirectUrl = null;

            if (client is not {
                Response : {} result
            })
Пример #4
0
 protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
 {
     responseLength    = -1;
     response.MimeType = "text/html";
     response.Status   = 200;
     redirectUrl       = null;
 }
Пример #5
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            // unknown content-length
            // no-redirect
            responseLength = -1;
            redirectUrl    = null;

            try
            {
                var headers = response.GetHeaderMap();
                headers.Add("Access-Control-Allow-Origin", "*");
                response.SetHeaderMap(headers);

                response.Status     = (int)_statusCode;
                response.MimeType   = _mime;
                response.StatusText = _statusText;
            }
            catch (Exception exception)
            {
                _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileProcessingError, null, exception, out _statusCode, out _statusText);
                response.Status     = (int)_statusCode;
                response.StatusText = _statusText;
                response.MimeType   = "text/plain";

                Logger.Instance.Log.LogError(exception, exception.Message);
            }
        }
Пример #6
0
        /// <summary>
        /// Send a POST request to the specified <see cref="Uri"/> and return the response body
        /// as a string in an asynchronous operation.
        /// </summary>
        /// <param name="requestUri">The <see cref="Uri"/> the request is sent to.</param>
        /// <param name="referrerUri">
        /// The <see cref="Uri"/> of the referring site for a request. Can be null.
        /// </param>
        /// <param name="referrerPolicy">
        /// The policy for how the Referrer HTTP header value will be sent during request.
        /// </param>
        /// <param name="headers">
        /// A <see cref="NameValueCollection"/> containing header name/value pairs associated with a request. Can be null.
        /// </param>
        /// <param name="content">The request content sent to the specified <see cref="Uri"/>.</param>
        /// <param name="cancellationToken">
        /// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public async Task <string> PostReadStringAsync(Uri requestUri, Uri referrerUri, CefReferrerPolicy referrerPolicy, CefPostData content, NameValueCollection headers, CancellationToken cancellationToken)
        {
            var request = await PostAsync(requestUri, referrerUri, referrerPolicy, content, headers, cancellationToken).ConfigureAwait(false);

            AssertSuccess(request);

            Stream responseStream = request.GetResponseStream();

            if (responseStream is null)
            {
                return(string.Empty);
            }

            CefResponse response = request.Response;

            if (response is null)
            {
                return(null);
            }

            Encoding encoding;

            try
            {
                encoding = Encoding.GetEncoding(response.Charset);
            }
            catch (ArgumentException)
            {
                encoding = this.DefaultEncoding;
            }
            return(new StreamReader(responseStream, encoding).ReadToEnd());
        }
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            // unknown content-length
            // no-redirect
            responseLength = -1;
            redirectUrl    = null;

            try
            {
                var headers = response.GetHeaderMap();
                headers.Add("Access-Control-Allow-Origin", "*");
                response.SetHeaderMap(headers);

                response.Status     = _status;
                response.MimeType   = _mime;
                response.StatusText = _statusText;
            }
            catch (Exception exception)
            {
                response.Status     = (int)HttpStatusCode.BadRequest;
                response.MimeType   = "text/plain";
                response.StatusText = "Resource loading error.";

                Logger.Instance.Log.LogError(exception, exception.Message);
            }
        }
Пример #8
0
    protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
    {
        redirectUrl    = string.Empty;
        responseLength = -1;

        response.MimeType   = MimeType;
        response.Status     = StatusCode;
        response.StatusText = StatusText;
        response.SetHeaderMap(Headers);

        if (!StringUtil.IsNullOrEmpty(Charset))
        {
            response.Charset = Charset ?? string.Empty;
        }

        if (ResponseLength.HasValue)
        {
            responseLength = ResponseLength.Value;
        }

        if (Stream is not null && Stream.CanSeek)
        {
            //ResponseLength property has higher precedence over Stream.Length
            if (ResponseLength is null || responseLength == 0)
            {
                //If no ResponseLength provided then attempt to infer the length
                responseLength = Stream.Length;
            }

            Stream.Position = 0;
        }
        ;
    }
Пример #9
0
        /// <summary>
        /// The get response headers.
        /// </summary>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <param name="responseLength">
        /// The response length.
        /// </param>
        /// <param name="redirectUrl">
        /// The redirect url.
        /// </param>
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            // unknown content-length
            // no-redirect
            responseLength = -1;
            redirectUrl    = null;

            try
            {
                var headers = response.GetHeaderMap();
                //headers.Add("Access-Control-Allow-Origin", "*");
                headers.Add("Accept-Ranges", "bytes");
                headers.Add("Content-Lenght", this.mFileBytes.Length.ToString());
                response.SetHeaderMap(headers);

                response.Status     = (int)HttpStatusCode.OK;
                response.MimeType   = this.mMime;
                response.StatusText = "OK";
            }
            catch (Exception exception)
            {
                response.Status     = (int)HttpStatusCode.BadRequest;
                response.MimeType   = "text/plain";
                response.StatusText = "Resource loading error.";

                Log.Error(exception);
            }
        }
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            if (response == null)
            {
                responseLength = -1;
                redirectUrl    = null;
                return;
            }

            String extension = Path.GetExtension(uri.LocalPath);

            if (extension.Length > 1 && extension.StartsWith("."))
            {
                extension = extension.Substring(1);
            }

            String mimeType;

            if (!MimeTypeManager.MimeTypes.TryGetValue(extension, out mimeType))
            {
                mimeType = "text/html";
            }

            response.Status     = 200;
            response.MimeType   = mimeType;
            response.StatusText = "OK";
            responseLength      = length;
            redirectUrl         = null; // no-redirect
        }
Пример #11
0
        /// <summary>
        /// The get response headers.
        /// </summary>
        /// <param name="response">
        /// The response.
        /// </param>
        /// <param name="responseLength">
        /// The response length.
        /// </param>
        /// <param name="redirectUrl">
        /// The redirect url.
        /// </param>
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            // unknown content-length
            // no-redirect
            responseLength = -1;
            redirectUrl    = null;

            try
            {
                HttpStatusCode status      = (mChromelyResponse != null) ? (HttpStatusCode)mChromelyResponse.Status : HttpStatusCode.BadRequest;
                string         errorStatus = (mChromelyResponse != null) ? mChromelyResponse.Data.ToString() : "Not Found";

                var headers = response.GetHeaderMap();
                headers.Add("Cache-Control", "private");
                headers.Add("Access-Control-Allow-Origin", "*");
                headers.Add("Access-Control-Allow-Methods", "GET,POST");
                headers.Add("Access-Control-Allow-Headers", "Content-Type");
                headers.Add("Content-Type", "application/json; charset=utf-8");
                response.SetHeaderMap(headers);

                response.Status     = (int)status;
                response.MimeType   = "application/json";
                response.StatusText = (status == HttpStatusCode.OK) ? "OK" : errorStatus;
            }
            catch (Exception exception)
            {
                Log.Error(exception);
            }
        }
Пример #12
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            responseLength = _responseBytes?.LongLength ?? 0;
            redirectUrl    = null;

            try
            {
                var statusCode = _apiResponse.StatusCode;

                var headers = response.GetHeaderMap();
                headers.Add("Cache-Control", "private");
                headers.Add("Access-Control-Allow-Origin", "*");
                headers.Add("Access-Control-Allow-Methods", "GET,POST");
                headers.Add("Access-Control-Allow-Headers", "Content-Type");
                headers.Add("Content-Type", "application/json; charset=utf-8");
                response.SetHeaderMap(headers);

                response.Status     = statusCode;
                response.MimeType   = "application/json";
                response.StatusText = (statusCode < 400 && statusCode >= 200) ? "OK" : "Error";
            }
            catch (Exception exception)
            {
                _logger.Error(exception);
            }
        }
Пример #13
0
        /// <summary>
        /// Notifies that the request has completed.
        /// </summary>
        /// <param name="request">The associated <see cref="CefUrlRequest"/>.</param>
        /// <remarks>
        /// Use the <see cref="CefUrlRequest.RequestStatus"/> to determine
        /// if the request was successful or not.
        /// </remarks>
        protected internal override void OnRequestComplete(CefUrlRequest request)
        {
            if (_stream != null)
            {
                try
                {
                    _stream.Flush();
                    if (_stream.CanSeek)
                    {
                        _stream.Seek(0, SeekOrigin.Begin);
                    }
                }
                catch (IOException ioe)
                {
                    SetException(ioe);
                }
            }

            _request               = request.Request;
            _response              = request.Response;
            _requestStatus         = request.RequestStatus;
            this.RequestError      = request.RequestError;
            this.ResponseWasCached = request.ResponseWasCached();

            IsCompleted = true;
            RequestOperation op = Volatile.Read(ref _activeOperation);

            if (op is null || op.continuation is null)
            {
                return;
            }

            ThreadPool.QueueUserWorkItem(cont => ((Action)cont)(), op.continuation);
        }
Пример #14
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            // unknown content-length
            // no-redirect
            responseLength = -1;
            redirectUrl    = null;

            try
            {
                var headers = response.GetHeaderMap();
                headers.Add("Access-Control-Allow-Origin", "*");
                response.SetHeaderMap(headers);

                response.Status     = (int)_chromelyResource.StatusCode;
                response.MimeType   = _chromelyResource.MimeType;
                response.StatusText = _chromelyResource.StatusText;
            }
            catch (Exception exception)
            {
                _chromelyResource   = _chromelyErrorHandler.HandleError(_fileInfo, exception);
                response.Status     = (int)_chromelyResource.StatusCode;
                response.MimeType   = _chromelyResource.MimeType;
                response.StatusText = _chromelyResource.StatusText;
            }
        }
Пример #15
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            if (response == null)
            {
                responseLength = -1;
                redirectUrl    = null;
                return;
            }

            string extension = Path.GetExtension(uri.LocalPath);

            if (extension.Length > 1 && extension.StartsWith("."))
            {
                extension = extension.Substring(1);
            }

            string mimeType;

            if (!MimeTypeManager.MimeTypes.TryGetValue(extension, out mimeType))
            {
                mimeType = "text/html";
            }

            API.Instance.Log("AssetSchemeHandler::GetResponseHeadlers File {0} mapped with mime type {1}", resolvedPath, mimeType);

            response.Status     = 200;
            response.MimeType   = mimeType;
            response.StatusText = "OK";
            responseLength      = length;
            redirectUrl         = null; // no-redirect
        }
Пример #16
0
 protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
 {
     response.SetHeaderMap(_source.IsStatic ? Staticfileheader : Dynamicfileheader);
     response.Status     = 200;
     response.MimeType   = _source.Mime;            // "text/html";
     response.StatusText = "OK";
     responseLength      = _source.Resource.Length; // unknown content-length
     redirectUrl         = null;                    // no-redirect
 }
Пример #17
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            responseLength = stream.Length;
            redirectUrl    = null;

            response.Status     = (int)HttpStatusCode.OK;
            response.StatusText = "OK";
            response.MimeType   = mimeType;
        }
Пример #18
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            var statusCode = _resourceResponse?.HttpStatus ?? System.Net.HttpStatusCode.BadRequest;

            if (_resourceResponse != null)
            {
                response.SetHeaderMap(_resourceResponse.Headers);
            }


            response.Status = (int)statusCode;

            redirectUrl = null;

            if (statusCode == System.Net.HttpStatusCode.OK)
            {
                responseLength    = _resourceResponse.Length;
                response.MimeType = _resourceResponse.MimeType;

                if (_isPartContent)
                {
                    response.SetHeaderByName("Accept-Ranges", "bytes", true);

                    var startPos = 0;
                    var endPos   = _resourceResponse.Length - 1;

                    if (_buffStartPostition.HasValue && _buffEndPostition.HasValue)
                    {
                        startPos = _buffStartPostition.Value;
                        endPos   = _buffStartPostition.Value;
                    }
                    else if (!_buffEndPostition.HasValue && _buffStartPostition.HasValue)
                    {
                        startPos = _buffStartPostition.Value;
                    }

                    response.SetHeaderByName("Content-Range", $"bytes {startPos}-{endPos}/{_resourceResponse.Length}", true);
                    response.SetHeaderByName("Content-Length", $"{endPos - startPos + 1}", true);


                    response.Status = 206;

                    Logger.Verbose($"[Content-Range]: {startPos}-{endPos}/{_resourceResponse.Length}");
                }


                response.SetHeaderByName("Content-Type", response.MimeType, true);

                response.SetHeaderByName(X_POWERED_BY, $"NanUI/{System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}", true);
            }
            else
            {
                responseLength = 0;
            }
        }
Пример #19
0
        // TODO: use OnBeforeResourceLoad to OnResourceResponse to detect resource loading, and waiting when all resources will be loaded
        protected override bool OnBeforeResourceLoad(CefBrowser browser, CefRequest request, out string redirectUrl, out CefStreamReader resourceStream, CefResponse response, int loadFlags)
        {
            var prevColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.DarkMagenta;
            Console.WriteLine("OnBeforeResourceLoad: {0}", request.GetURL());
            Console.ForegroundColor = prevColor;

            redirectUrl = null;
            resourceStream = null;
            return false;
        }
Пример #20
0
        protected override void OnResourceResponse(CefBrowser browser, string url, CefResponse response, out CefContentFilter filter)
        {
            var prevColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("OnResourceResponse: {0} ({1})", url, response.GetHeader("Content-Length"));
            Console.ForegroundColor = prevColor;

            response.GetHeaderMap().Append("Access-Control-Allow-Origin", "*");

            filter = null;
            // filter = new CefWebProgressContentFilter();
        }
 protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
 {
     response.MimeType   = MimeType;
     response.Status     = StatusCode;
     response.StatusText = StatusText;
     if (Headers.Count > 0)
     {
         response.SetHeaderMap(Headers);
     }
     responseLength = (Data == null ? 0 : Data.LongLength);
     redirectUrl    = null;
 }
Пример #22
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            response.MimeType = "text/html";
            response.Status = 200;
            response.StatusText = "OK, hello from handler!";

            var headers = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase);
            headers.Add("Cache-Control", "private");
            response.SetHeaderMap(headers);

            responseLength = responseData.LongLength;
            redirectUrl = null;
        }
Пример #23
0
        protected override void OnResourceResponse(CefBrowser browser, string url, CefResponse response, out CefContentFilter filter)
        {
            var prevColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine("OnResourceResponse: {0} ({1})", url, response.GetHeader("Content-Length"));
            Console.ForegroundColor = prevColor;

            response.GetHeaderMap().Append("Access-Control-Allow-Origin", "*");

            filter = null;
            // filter = new CefWebProgressContentFilter();
        }
Пример #24
0
                protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
                {
                    response.MimeType   = "text/html";
                    response.Status     = 200;
                    response.StatusText = "OK";

                    var headers = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase);

                    headers.Add("Cache-Control", "private");
                    response.SetHeaderMap(headers);

                    responseLength = FStream.Length;
                    redirectUrl    = null;
                }
Пример #25
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            response.MimeType   = "application/javascript";
            response.Status     = 200;
            response.StatusText = "OK, hello from handler!";

            var headers = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase);

            headers.Add("Cache-Control", "private");
            response.SetHeaderMap(headers);

            responseLength = responseData.LongLength;
            redirectUrl    = null;
        }
Пример #26
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, ref string redirectUrl)
        {
            responseLength = this.responseLength;

            if (responseLength != -1)
            {
                var headers = new CefStringMultiMap();
                headers.Append("Content-Length", responseLength.ToString());
                response.SetHeaderMap(headers);
            }

            response.SetStatus(this.status);
            response.SetStatusText(this.statusText);
            response.SetMimeType(this.mimeType);
        }
Пример #27
0
        /// <summary>
        /// Sends the request to the server as an asynchronous operation.<para/>
        /// For requests originating from the browser process:
        /// <list type="bullet">
        /// <item>
        /// <description>
        /// It may be intercepted by the client via CefResourceRequestHandler or
        /// CefSchemeHandlerFactory;
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// POST data may only contain only a single element of type
        /// <see cref="CefPostDataElementType.File"/> or <see cref="CefPostDataElementType.Bytes"/>.
        /// </description>
        /// </item>
        /// </list>
        /// For requests originating from the render process:
        /// <list type="bullet">
        /// <item>
        /// <description>
        /// It cannot be intercepted by the client so only http(s) and blob schemes
        /// are supported.
        /// </description>
        /// </item>
        /// <item>
        /// <description>
        /// POST data may only contain a single element of type <see cref="CefPostDataElementType.Bytes"/>.
        /// </description>
        /// </item>
        /// </list>
        /// </summary>
        /// <param name="request">
        /// The <see cref="CefRequest"/> object to send. It will be marked as read-only after calling
        /// this function.
        /// </param>
        /// <param name="context">
        /// A request context or null, if <paramref name="context"/> is empty the global
        /// request context will be used. For requests originating from the render process
        /// this parameter must be null.
        /// </param>
        /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        /// <remarks>
        /// This operation will not block. The returned <see cref="Task"/> object will complete once
        /// the entire response including content is read.
        /// </remarks>
        public async Task SendAsync(CefRequest request, CefRequestContext context, CancellationToken cancellationToken)
        {
            if (CefNetApplication.ProcessType != ProcessType.Main && context != null)
            {
                throw new ArgumentOutOfRangeException(nameof(context));
            }

            if (Interlocked.CompareExchange(ref _activeOperation, new RequestOperation(), null) != null)
            {
                throw new InvalidOperationException();
            }

            _request   = request;
            _response  = null;
            _exception = null;
            if (_stream != null)
            {
                _stream.Dispose();
                _stream = null;
            }
            _requestStatus         = CefUrlRequestStatus.Unknown;
            this.RequestError      = CefErrorCode.None;
            this.ResponseWasCached = false;
            this.IsCompleted       = false;

            try
            {
                _activeOperation.request = await CreateUrlRequest(request, context, cancellationToken).ConfigureAwait(false);

                using (cancellationToken.Register(Abort))
                {
                    await this;
                }
            }
            finally
            {
                Interlocked.Exchange(ref _activeOperation, null);
            }

            Exception exception = Volatile.Read(ref _exception);

            if (exception is null)
            {
                return;
            }

            ExceptionDispatchInfo.Capture(exception).Throw();
        }
Пример #28
0
        protected internal sealed override void GetResponseHeaders(CefResponse response, ref long responseLength, ref string redirectUrl)
        {
            response.Status   = (int)this.StatusCode;
            response.Charset  = "utf-8";
            response.MimeType = this.MimeType;
            responseLength    = _data.Length;

            if (_headers != null && _headers.Count > 0)
            {
                using (var map = new CefStringMultimap())
                {
                    map.Add(_headers);
                    response.SetHeaderMap(map);
                }
            }
        }
Пример #29
0
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            responseLength = this.responseLength;
            redirectUrl    = null;

            if (responseLength != -1)
            {
                var headers = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase);
                headers.Add("Content-Length", responseLength.ToString());
                response.SetHeaderMap(headers);
            }

            response.Status     = this.status;
            response.StatusText = this.statusText;
            response.MimeType   = this.mimeType;
        }
Пример #30
0
        /// <summary>
        /// Gets the response headers.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="responseLength"></param>
        /// <param name="redirectUrl"></param>
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            redirectUrl = null;

            response.Status     = 200;
            response.StatusText = "OK";
            response.MimeType   = "application/json";
            response.SetHeaderMap(new NameValueCollection {
                { "Access-Control-Allow-Origin", "*" }
            });

            var nativeResponse = new NativeResponse();

            // exception
            if (Exception != null)
            {
                nativeResponse.Type      = NativeResponseType.Exception;
                nativeResponse.Value     = null;
                nativeResponse.Exception = ExceptionUtility.CreateJavascriptException(Exception);
            }

            // ok
            else
            {
                if (ResponseValue == Undefined.Value)
                {
                    nativeResponse.Type  = NativeResponseType.Undefined;
                    nativeResponse.Value = null;
                }
                else
                {
                    nativeResponse.Type  = NativeResponseType.Value;
                    nativeResponse.Value = ResponseValue;
                }

                nativeResponse.Exception = null;
            }

            Data           = JsonUtility.SerializeToByteJson(nativeResponse);
            responseLength = Data.Length;
        }
Пример #31
0
            protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string?redirectUrl)
            {
                response.Status     = (int)_code;
                response.StatusText = _code.ToString();
                response.MimeType   = _contentType;

                if (_stream.CanSeek)
                {
                    responseLength = _stream.Length;
                }
                else
                {
                    responseLength = -1;
                }

                redirectUrl = default;
            }
Пример #32
0
        /// <summary>
        /// Gets the response headers.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="responseLength"></param>
        /// <param name="redirectUrl"></param>
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            redirectUrl = null;

            if (Exception != null)
            {
                Data = Encoding.UTF8.GetBytes(string.Format(ResourceUtility.GetResourceAsString("Views/ContentRequestException.html"),
                                                            Url,
                                                            Exception.ToString().Replace(Environment.NewLine, "<br>")));

                responseLength      = Data.Length;
                response.Status     = 500;
                response.StatusText = "Internal Server Error";
                response.MimeType   = "text/html";
            }
            else if (Data != null)
            {
                responseLength      = Data.Length;
                response.Status     = 200;
                response.StatusText = "OK";

                // mime type
                response.MimeType = "application/octet-stream";
                var extension = Path.GetExtension(Url);

                if (!string.IsNullOrWhiteSpace(extension) && Application.Current.MimeTypes.ContainsKey(extension))
                {
                    response.MimeType = Application.Current.MimeTypes[extension];
                }
            }
            else
            {
                Data = Encoding.UTF8.GetBytes(string.Format(ResourceUtility.GetResourceAsString("Views/ContentNotFound.html"), Url));

                responseLength      = Data.Length;
                response.Status     = 404;
                response.StatusText = "Not Found";
                response.MimeType   = "text/html";
            }
        }
Пример #33
0
        /// <summary>
        /// Retrieve response header information. If the response length is not known
        /// set |response_length| to -1 and ReadResponse() will be called until it
        /// returns false. If the response length is known set |response_length|
        /// to a positive value and ReadResponse() will be called until it returns
        /// false or the specified number of bytes have been read. Use the |response|
        /// object to set the mime type, http status code and other optional header
        /// values. To redirect the request to a new URL set |redirectUrl| to the new
        /// URL.
        /// </summary>
        /// <param name="response"></param>
        /// <param name="responseLength"></param>
        /// <param name="redirectUrl"></param>
        protected override void GetResponseHeaders(CefResponse response, out long responseLength, out string redirectUrl)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            response.MimeType   = "text/html";
            response.Status     = 200;
            response.StatusText = "OK, hello from handler!";

            var headers = new NameValueCollection(StringComparer.OrdinalIgnoreCase);

            headers.Add("Cache-Control", "private");
            response.SetHeaderMap(headers);

            responseLength = responseData.LongLength;
            redirectUrl    = null;
        }