示例#1
0
        /// <inheritdoc />
        public void Append(string key, string value)
        {
            var setCookieHeaderValue = new SetCookieHeaderValue(
                Uri.EscapeDataString(key),
                Uri.EscapeDataString(value))
            {
                Path = "/"
            };

            string cookieValue;

            if (_builderPool == null)
            {
                cookieValue = setCookieHeaderValue.ToString();
            }
            else
            {
                var stringBuilder = _builderPool.Get();
                try
                {
                    setCookieHeaderValue.AppendToStringBuilder(stringBuilder);
                    cookieValue = stringBuilder.ToString();
                }
                finally
                {
                    _builderPool.Return(stringBuilder);
                }
            }

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
        }
        public void Append(HttpResponse response, string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            SetCookieHeaderValue cookieHeaderValue = new SetCookieHeaderValue(Uri.EscapeDataString(key), Uri.EscapeDataString(value));
            string domain = options.Domain;

            cookieHeaderValue.Domain = domain;
            string path = options.Path;

            cookieHeaderValue.Path = path;
            DateTimeOffset?expires = options.Expires;

            cookieHeaderValue.Expires = expires;
            int num1 = options.Secure ? 1 : 0;

            cookieHeaderValue.Secure = num1 != 0;
            int num2 = options.HttpOnly ? 1 : 0;

            cookieHeaderValue.HttpOnly = num2 != 0;
            var cookieVal = (StringValues)cookieHeaderValue.ToString() + "; SameSite=Lax";

            response.Headers["Set-Cookie"] = StringValues.Concat(response.Headers["Set-Cookie"], cookieVal);
        }
        public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var template = new SetCookieHeaderValue(key)
            {
                Domain   = options.Domain,
                Expires  = options.Expires,
                HttpOnly = options.HttpOnly,
                Path     = options.Path,
                Secure   = options.Secure,
            };

            var templateLength = template.ToString().Length;

            value = value ?? string.Empty;

            var responseCookies = context.Response.Cookies;

            if (!_cookieManagerOptions.ChunkSize.HasValue || _cookieManagerOptions.ChunkSize.Value > templateLength + value.Length)
            {
                responseCookies.Append(key, value, options);
            }
            else if (_cookieManagerOptions.ChunkSize.Value < templateLength + 10)
            {
                throw new InvalidOperationException("The cookie key and options are larger than ChunksSize, leaving no room for data.");
            }
            else
            {
                var dataSizePerCookie = _cookieManagerOptions.ChunkSize.Value - templateLength - 3;
                var cookieChunkCount  = (int)Math.Ceiling(value.Length * 1.0 / dataSizePerCookie);

                responseCookies.Append(key, ChunkCountPrefix + cookieChunkCount.ToString(CultureInfo.InvariantCulture), options);

                var offset = 0;
                for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
                {
                    var remainingLength = value.Length - offset;
                    var length          = Math.Min(dataSizePerCookie, remainingLength);
                    var segment         = value.Substring(offset, length);
                    offset += length;

                    responseCookies.Append(key + ChunkKeySuffix + chunkId.ToString(CultureInfo.InvariantCulture), segment, options);
                }
            }
        }
示例#4
0
        /// <inheritdoc />
        public void Append(string key, string value)
        {
            var setCookieHeaderValue = new SetCookieHeaderValue(
                Uri.EscapeDataString(key),
                Uri.EscapeDataString(value))
            {
                Path = "/"
            };
            var cookieValue = setCookieHeaderValue.ToString();

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
        }
示例#5
0
    /// <inheritdoc />
    public void Append(string key, string value)
    {
        var setCookieHeaderValue = new SetCookieHeaderValue(
            _enableCookieNameEncoding ? Uri.EscapeDataString(key) : key,
            Uri.EscapeDataString(value))
        {
            Path = "/"
        };
        var cookieValue = setCookieHeaderValue.ToString();

        Headers.SetCookie = StringValues.Concat(Headers.SetCookie, cookieValue);
    }
示例#6
0
        /// <inheritdoc />
        public void Append(string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var setCookieHeaderValue = new SetCookieHeaderValue(
                Uri.EscapeDataString(key),
                Uri.EscapeDataString(value))
            {
                Domain   = options.Domain,
                Path     = options.Path,
                Expires  = options.Expires,
                Secure   = options.Secure,
                HttpOnly = options.HttpOnly,
            };

            string cookieValue;

            if (_builderPool == null)
            {
                cookieValue = setCookieHeaderValue.ToString();
            }
            else
            {
                var stringBuilder = _builderPool.Get();
                try
                {
                    setCookieHeaderValue.AppendToStringBuilder(stringBuilder);
                    cookieValue = stringBuilder.ToString();
                }
                finally
                {
                    _builderPool.Return(stringBuilder);
                }
            }

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
        }
示例#7
0
        public static void AppendWithoutEscapes(this IHeaderDictionary headers, string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var setCookieHeaderValue = new SetCookieHeaderValue("")
            {
                Domain   = options.Domain,
                Path     = options.Path,
                Expires  = options.Expires,
                Secure   = options.Secure,
                SameSite = (Microsoft.Net.Http.Headers.SameSiteMode)options.SameSite,
                HttpOnly = options.HttpOnly
            };

            var cookie      = key + "=" + value;
            var cookieValue = cookie + setCookieHeaderValue.ToString().Substring(1);

            headers[HeaderNames.SetCookie] = StringValues.Concat(headers[HeaderNames.SetCookie], cookieValue);
        }
示例#8
0
    /// <inheritdoc />
    public void Append(string key, string value, CookieOptions options)
    {
        if (options == null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        // SameSite=None cookies must be marked as Secure.
        if (!options.Secure && options.SameSite == SameSiteMode.None)
        {
            if (_logger == null)
            {
                var services = _features.Get <Features.IServiceProvidersFeature>()?.RequestServices;
                _logger = services?.GetService <ILogger <ResponseCookies> >();
            }

            if (_logger != null)
            {
                Log.SameSiteCookieNotSecure(_logger, key);
            }
        }

        var setCookieHeaderValue = new SetCookieHeaderValue(
            _enableCookieNameEncoding ? Uri.EscapeDataString(key) : key,
            Uri.EscapeDataString(value))
        {
            Domain   = options.Domain,
            Path     = options.Path,
            Expires  = options.Expires,
            MaxAge   = options.MaxAge,
            Secure   = options.Secure,
            SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite,
            HttpOnly = options.HttpOnly
        };

        var cookieValue = setCookieHeaderValue.ToString();

        Headers.SetCookie = StringValues.Concat(Headers.SetCookie, cookieValue);
    }
        /// <inheritdoc />
        public void Append(string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var setCookieHeaderValue = new SetCookieHeaderValue(
                Uri.EscapeDataString(key),
                Uri.EscapeDataString(value))
            {
                Domain   = options.Domain,
                Path     = options.Path,
                Expires  = options.Expires,
                Secure   = options.Secure,
                HttpOnly = options.HttpOnly,
            };

            var cookieValue = setCookieHeaderValue.ToString();

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
        }
示例#10
0
        /// <inheritdoc />
        public void Append(string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var setCookieHeaderValue = new SetCookieHeaderValue(
                _enableCookieNameEncoding ? Uri.EscapeDataString(key) : key,
                Uri.EscapeDataString(value))
            {
                Domain   = options.Domain,
                Path     = options.Path,
                Expires  = options.Expires,
                MaxAge   = options.MaxAge,
                Secure   = options.Secure,
                SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite,
                HttpOnly = options.HttpOnly
            };

            var cookieValue = setCookieHeaderValue.ToString();

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
        }
示例#11
0
        public static void AppendWithoutEncoding(this IResponseCookies responseCookies, string key, string value, CookieOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var setCookieHeaderValue = new SetCookieHeaderValue(key, value)
            {
                Domain   = options.Domain,
                Path     = options.Path,
                Expires  = options.Expires,
                MaxAge   = options.MaxAge,
                Secure   = options.Secure,
                SameSite = (SameSiteMode)options.SameSite,
                HttpOnly = options.HttpOnly
            };

            var cookieValue = setCookieHeaderValue.ToString();

            var headers = GetHeaders(responseCookies);

            headers[HeaderNames.SetCookie] = StringValues.Concat(headers[HeaderNames.SetCookie], cookieValue);
        }
        /// <summary>
        /// Add a new cookie and value
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Append(string key, string value)
        {
            var setCookieHeaderValue = new SetCookieHeaderValue(
                UrlEncoder.Default.UrlEncode(key),
                UrlEncoder.Default.UrlEncode(value))
            {
                Path = "/"
            };

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], setCookieHeaderValue.ToString());
        }
示例#13
0
        /// <summary>
        /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit
        /// then it will be broken down into multiple cookies as follows:
        /// Set-Cookie: CookieName=chunks:3; path=/
        /// Set-Cookie: CookieNameC1=Segment1; path=/
        /// Set-Cookie: CookieNameC2=Segment2; path=/
        /// Set-Cookie: CookieNameC3=Segment3; path=/
        /// </summary>
        /// <param name="context"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public void AppendResponseCookie([NotNull] HttpContext context, [NotNull] string key, string value, [NotNull] CookieOptions options)
        {
            var escapedKey = Encoder.UrlEncode(key);

            var template = new SetCookieHeaderValue(escapedKey)
            {
                Domain   = options.Domain,
                Expires  = options.Expires,
                HttpOnly = options.HttpOnly,
                Path     = options.Path,
                Secure   = options.Secure,
            };

            var templateLength = template.ToString().Length;

            value = value ?? string.Empty;
            var quoted = false;

            if (IsQuoted(value))
            {
                quoted = true;
                value  = RemoveQuotes(value);
            }
            var escapedValue = Encoder.UrlEncode(value);

            // Normal cookie
            var responseHeaders = context.Response.Headers;

            if (!ChunkSize.HasValue || ChunkSize.Value > templateLength + escapedValue.Length + (quoted ? 2 : 0))
            {
                template.Value = quoted ? Quote(escapedValue) : escapedValue;
                responseHeaders.AppendValues(Constants.Headers.SetCookie, template.ToString());
            }
            else if (ChunkSize.Value < templateLength + (quoted ? 2 : 0) + 10)
            {
                // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX".
                // No room for data, we can't chunk the options and name
                throw new InvalidOperationException(Resources.Exception_CookieLimitTooSmall);
            }
            else
            {
                // Break the cookie down into multiple cookies.
                // Key = CookieName, value = "Segment1Segment2Segment2"
                // Set-Cookie: CookieName=chunks:3; path=/
                // Set-Cookie: CookieNameC1="Segment1"; path=/
                // Set-Cookie: CookieNameC2="Segment2"; path=/
                // Set-Cookie: CookieNameC3="Segment3"; path=/
                var dataSizePerCookie = ChunkSize.Value - templateLength - (quoted ? 2 : 0) - 3; // Budget 3 chars for the chunkid.
                var cookieChunkCount  = (int)Math.Ceiling(escapedValue.Length * 1.0 / dataSizePerCookie);

                template.Value = "chunks:" + cookieChunkCount.ToString(CultureInfo.InvariantCulture);
                responseHeaders.AppendValues(Constants.Headers.SetCookie, template.ToString());

                var chunks = new string[cookieChunkCount];
                var offset = 0;
                for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
                {
                    var remainingLength = escapedValue.Length - offset;
                    var length          = Math.Min(dataSizePerCookie, remainingLength);
                    var segment         = escapedValue.Substring(offset, length);
                    offset += length;

                    template.Name       = escapedKey + "C" + chunkId.ToString(CultureInfo.InvariantCulture);
                    template.Value      = quoted ? Quote(segment) : segment;
                    chunks[chunkId - 1] = template.ToString();
                }
                responseHeaders.AppendValues(Constants.Headers.SetCookie, chunks);
            }
        }
 /// <summary>
 /// Sets cookie <paramref name="cookie"/> to the HTTP response.
 /// </summary>
 /// <param name="response">HTTP response to which the cookie is set.</param>
 /// <param name="cookie">The cookie to be set.</param>
 /// <returns>Returns back original HTTP response for fluent API.</returns>
 /// <remarks><para>This method is available only in .NET Core version of the library.</para></remarks>
 public static HttpResponseMessage SetCookie(this HttpResponseMessage response, SetCookieHeaderValue cookie)
 {
     response.Headers.Add(HeaderNames.SetCookie, cookie.ToString());
     return(response);
 }
示例#15
0
        /// <summary>
        /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit
        /// then it will be broken down into multiple cookies as follows:
        /// Set-Cookie: CookieName=chunks-3; path=/
        /// Set-Cookie: CookieNameC1=Segment1; path=/
        /// Set-Cookie: CookieNameC2=Segment2; path=/
        /// Set-Cookie: CookieNameC3=Segment3; path=/
        /// </summary>
        /// <param name="context"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="options"></param>
        public void AppendResponseCookie(HttpContext context, string key, string value, CookieOptions options)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var template = new SetCookieHeaderValue(key)
            {
                Domain   = options.Domain,
                Expires  = options.Expires,
                HttpOnly = options.HttpOnly,
                Path     = options.Path,
                Secure   = options.Secure,
            };

            var templateLength = template.ToString().Length;

            value = value ?? string.Empty;

            // Normal cookie
            var responseCookies = context.Response.Cookies;

            if (!_cookieManagerOptions.ChunkSize.HasValue || _cookieManagerOptions.ChunkSize.Value > templateLength + value.Length)
            {
                responseCookies.Append(key, value, options);
            }
            else if (_cookieManagerOptions.ChunkSize.Value < templateLength + 10)
            {
                // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX".
                // No room for data, we can't chunk the options and name
                throw new InvalidOperationException("The cookie key and options are larger than ChunksSize, leaving no room for data.");
            }
            else
            {
                // Break the cookie down into multiple cookies.
                // Key = CookieName, value = "Segment1Segment2Segment2"
                // Set-Cookie: CookieName=chunks-3; path=/
                // Set-Cookie: CookieNameC1="Segment1"; path=/
                // Set-Cookie: CookieNameC2="Segment2"; path=/
                // Set-Cookie: CookieNameC3="Segment3"; path=/
                var dataSizePerCookie = _cookieManagerOptions.ChunkSize.Value - templateLength - 3; // Budget 3 chars for the chunkid.
                var cookieChunkCount  = (int)Math.Ceiling(value.Length * 1.0 / dataSizePerCookie);

                responseCookies.Append(key, ChunkCountPrefix + cookieChunkCount.ToString(CultureInfo.InvariantCulture), options);

                var offset = 0;
                for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++)
                {
                    var remainingLength = value.Length - offset;
                    var length          = Math.Min(dataSizePerCookie, remainingLength);
                    var segment         = value.Substring(offset, length);
                    offset += length;

                    responseCookies.Append(key + ChunkKeySuffix + chunkId.ToString(CultureInfo.InvariantCulture), segment, options);
                }
            }
        }
示例#16
0
        public static bool Request(HtcHttpContext httpContext, string filename, int timeout)
        {
            //httpContext.Response.ContentType = "text/html; charset=utf-8";
            using (var phpProcess = new Process()) {
                phpProcess.StartInfo.FileName = PhpProcessor.PhpCgiExec;
                //var pathVars = phpProcess.StartInfo.EnvironmentVariables["Path"];
                var queryString = httpContext.Request.QueryString;
                if (!string.IsNullOrEmpty(queryString))
                {
                    queryString = queryString.Remove(0, 1);
                }
                //queryString = Uri.UnescapeDataString(queryString);
                //phpProcess.StartInfo.EnvironmentVariables.Clear();
                phpProcess.StartInfo.EnvironmentVariables.Add("PHPRC", PhpProcessor.PhpPath);
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_HOST", httpContext.Request.Headers.GetValueOrDefault("Host"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_CONNECTION", httpContext.Request.Headers.GetValueOrDefault("Connection"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_UPGRADE_INSECURE_REQUESTS", httpContext.Request.Headers.GetValueOrDefault("Upgrade-Insecure-Requests"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_USER_AGENT", httpContext.Request.Headers.GetValueOrDefault("User-Agent"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_DNT", httpContext.Request.Headers.GetValueOrDefault("DNT"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_ACCEPT", httpContext.Request.Headers.GetValueOrDefault("Accept"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_ACCEPT_ENCODING", httpContext.Request.Headers.GetValueOrDefault("Accept-Encoding"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_ACCEPT_LANGUAGE", httpContext.Request.Headers.GetValueOrDefault("Accept-Language"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_COOKIE", httpContext.Request.Headers.GetValueOrDefault("Cookie"));
                //phpProcess.StartInfo.EnvironmentVariables.Add("PATH", pathVars);
                phpProcess.StartInfo.EnvironmentVariables.Add("SERVER_SOFTWARE", "HtcSharp/1.2");
                phpProcess.StartInfo.EnvironmentVariables.Add("SERVER_SIGNATURE", $"<address>HtcSharp/1.0 Server at {httpContext.ServerInfo.Domain} Port {httpContext.Connection.RemotePort}</address>");
                phpProcess.StartInfo.EnvironmentVariables.Add("SERVER_ADDR", httpContext.Request.Host);
                phpProcess.StartInfo.EnvironmentVariables.Add("SERVER_NAME", httpContext.Request.Host);
                phpProcess.StartInfo.EnvironmentVariables.Add("SERVER_PORT", httpContext.Connection.RemotePort.ToString());
                phpProcess.StartInfo.EnvironmentVariables.Add("REMOTE_ADDR", httpContext.Connection.RemoteIpAddress.ToString());
                phpProcess.StartInfo.EnvironmentVariables.Add("DOCUMENT_ROOT", httpContext.ServerInfo.RootPath.Replace(@"\", "/"));
                phpProcess.StartInfo.EnvironmentVariables.Add("REQUEST_SCHEME", httpContext.Request.Scheme);
                phpProcess.StartInfo.EnvironmentVariables.Add("CONTEXT_DOCUMENT_ROOT", httpContext.ServerInfo.RootPath.Replace(@"\", "/"));
                phpProcess.StartInfo.EnvironmentVariables.Add("SCRIPT_FILENAME", filename);
                phpProcess.StartInfo.EnvironmentVariables.Add("REMOTE_PORT", httpContext.Connection.RemotePort.ToString());
                phpProcess.StartInfo.EnvironmentVariables.Add("GATEWAY_INTERFACE", "CGI/1.1");
                phpProcess.StartInfo.EnvironmentVariables.Add("SERVER_PROTOCOL", "HTTP/1.1");
                phpProcess.StartInfo.EnvironmentVariables.Add("REQUEST_METHOD", httpContext.Request.Method.ToString());
                phpProcess.StartInfo.EnvironmentVariables.Add("QUERY_STRING", queryString);
                phpProcess.StartInfo.EnvironmentVariables.Add("REQUEST_URI", httpContext.Request.RequestPath);
                phpProcess.StartInfo.EnvironmentVariables.Add("SCRIPT_NAME", httpContext.Request.RequestFilePath);
                phpProcess.StartInfo.EnvironmentVariables.Add("PHP_SELF", httpContext.Request.RequestFilePath); // Maybe the script file ??
                phpProcess.StartInfo.EnvironmentVariables.Add("REDIRECT_STATUS", "200");
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTP_REFERER", httpContext.Request.Headers.GetValueOrDefault("Referer"));
                phpProcess.StartInfo.EnvironmentVariables.Add("CONTENT_LENGTH", httpContext.Request.ContentLength.ToString());
                phpProcess.StartInfo.EnvironmentVariables.Add("CONTENT_TYPE", httpContext.Request.Headers.GetValueOrDefault("Content-Type"));
                phpProcess.StartInfo.EnvironmentVariables.Add("HTTPS", httpContext.Request.IsHttps ? "1" : "0");
                phpProcess.StartInfo.EnvironmentVariables.Add("REMOTE_HOST", httpContext.Request.Host);
                phpProcess.StartInfo.EnvironmentVariables.Add("CONTEXT_PREFIX", "");
                //phpProcess.StartInfo.EnvironmentVariables.Add("PATH_INFO", httpContext.Request.RequestPath);
                //phpProcess.StartInfo.EnvironmentVariables.Add("PATH_TRANSLATED", httpContext.Request.TranslatedPath);

                phpProcess.StartInfo.UseShellExecute        = false;
                phpProcess.StartInfo.RedirectStandardInput  = true;
                phpProcess.StartInfo.RedirectStandardOutput = true;
                phpProcess.StartInfo.RedirectStandardError  = true;
                phpProcess.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                var isResponse = false;
                phpProcess.Start();
                httpContext.Request.InputStream.CopyTo(phpProcess.StandardInput.BaseStream);
                phpProcess.StandardInput.BaseStream.Flush();
                phpProcess.StandardInput.Flush();
                //try {
                while (!phpProcess.StandardOutput.EndOfStream)
                {
                    var line = phpProcess.StandardOutput.ReadLine();
                    if (line == null)
                    {
                        continue;
                    }
                    if (line == "" && isResponse == false)
                    {
                        isResponse = true;
                        continue;
                    }
                    if (isResponse)
                    {
                        httpContext.Response.Write(line + Environment.NewLine);
                    }
                    else
                    {
                        //var tag = line.Split(new[] {':'}, 2);
                        //tag[1] = tag[1].Remove(0, 1);
                        //httpContext.Response.Headers.Add(tag[0], tag[1]);
                        //Logger.Info($"{tag[0]}=>{tag[1]}");
                        //Logger.Info($"{line}");
                        var tag = line.Split(new[] { ':' }, 2);
                        tag[1] = tag[1].Remove(0, 1);
                        switch (tag[0])
                        {
                        case "Location":
                            httpContext.Response.Redirect(tag[1]);
                            break;

                        case "Set-Cookie":
                            var cookieOptions = new CookieOptions()
                            {
                                SameSite = SameSiteMode.None
                            };
                            var cookieData           = tag[1].Split(';', 2);
                            var cookieKeyValue       = cookieData[0].Split('=', 2);
                            var setCookieHeaderValue = new SetCookieHeaderValue(Uri.UnescapeDataString(cookieKeyValue[0]), Uri.UnescapeDataString(cookieKeyValue[1]));
                            foreach (var cookieConfig in cookieData[1].Split(';'))
                            {
                                var config = cookieConfig.Split('=', 2);
                                config[0] = config[0].Remove(0, 1);
                                if (config[0].Equals("Max-Age", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    setCookieHeaderValue.MaxAge = TimeSpan.FromSeconds(int.Parse(config[1]));
                                }
                                else if (config[0].Equals("path", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    setCookieHeaderValue.Path = config[1];
                                }
                                else if (config[0].Equals("domain", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    setCookieHeaderValue.Domain = config[1];
                                }
                                else if (config[0].Equals("HttpOnly", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    setCookieHeaderValue.HttpOnly = true;
                                }
                                else if (config[0].Equals("expires", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    setCookieHeaderValue.Expires = DateTimeOffset.Parse(config[1]);
                                }
                                else if (config[0].Equals("SameSite", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    setCookieHeaderValue.SameSite = Microsoft.Net.Http.Headers.SameSiteMode.Lax;
                                }
                            }
                            if (cookieKeyValue[1] == "+")
                            {
                                cookieKeyValue[1] = httpContext.Request.RequestTimestamp.ToString();
                            }
                            //Logger.Info($"{Uri.UnescapeDataString(cookieKeyValue[0])}: {Uri.UnescapeDataString(cookieKeyValue[1])}");
                            var cookieValue = setCookieHeaderValue.ToString();
                            httpContext.Response.InternalAspNetResponse.Headers[HeaderNames.SetCookie] = StringValues.Concat(httpContext.Response.InternalAspNetResponse.Headers[HeaderNames.SetCookie], cookieValue);
                            break;

                        default:
                            if (httpContext.Response.Headers.ContainsKey(tag[0]))
                            {
                                httpContext.Response.Headers[tag[0]] = string.Concat(httpContext.Response.Headers[tag[0]], tag[1]);
                            }
                            else
                            {
                                httpContext.Response.Headers.Add(tag[0], tag[1]);
                            }
                            break;
                        }
                    }
                }
                //} catch(Exception ex) {
                //    throw ex;
                //httpContext.Response.Write(phpProcess.StandardOutput.ReadToEnd());
                //}
                phpProcess.WaitForExit();
                return(false);
            }
        }
示例#17
0
 public void SetCookieHeaderValue_ToString(SetCookieHeaderValue input, string expectedValue)
 {
     Assert.Equal(expectedValue, input.ToString());
 }