/// <summary>
        /// Given the provided list of header value strings, return a comma-separated list of key
        /// name/value pairs with the provided keyName and keyValue. If the initial header value
        /// string contains the key name, then the original key value should be replaced with the
        /// provided key value. If the initial header value strings don't contain the key name,
        /// then the key name/value pair should be added to the comma-separated list and returned.
        /// </summary>
        /// <param name="currentHeaders">The existing header values that the key/value pair should be added to.</param>
        /// <param name="key">The name of the key to add.</param>
        /// <param name="value">The value of the key to add.</param>
        /// <returns>The result of setting the provided key name/value pair into the provided headerValues.</returns>
        public static StringValues SetHeaderKeyValue(string[] currentHeaders, string key, string value)
        {
            if (currentHeaders != null)
            {
                for (int index = 0; index < currentHeaders.Length; index++)
                {
                    if (HeaderMatchesKey(currentHeaders[index], key))
                    {
                        currentHeaders[index] = string.Concat(key, "=", value);
                        return(currentHeaders);
                    }
                }

                return(StringValues.Concat(currentHeaders, string.Concat(key, "=", value)));
            }
            else
            {
                return(string.Concat(key, "=", value));
            }
        }
Exemplo n.º 2
0
    /// <inheritdoc />
    ValueTask IOutputCachePolicy.CacheRequestAsync(OutputCacheContext context, CancellationToken cancellationToken)
    {
        // No vary by query?
        if (_queryKeys.Count == 0)
        {
            context.CacheVaryByRules.QueryKeys = _queryKeys;
            return(ValueTask.CompletedTask);
        }

        // If the current key is "*" (default) replace it
        if (context.CacheVaryByRules.QueryKeys.Count == 1 && string.Equals(context.CacheVaryByRules.QueryKeys[0], "*", StringComparison.Ordinal))
        {
            context.CacheVaryByRules.QueryKeys = _queryKeys;
            return(ValueTask.CompletedTask);
        }

        context.CacheVaryByRules.QueryKeys = StringValues.Concat(context.CacheVaryByRules.QueryKeys, _queryKeys);

        return(ValueTask.CompletedTask);
    }
Exemplo n.º 3
0
        private void AddClearInitFilters(IGridColumn column)
        {
            if (ComponentOptions.AllowMultipleFilters)
            {
                if (column.InitialFilterSettings != ColumnFilterValue.Null)
                {
                    if (_query.ContainsKey(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter))
                    {
                        StringValues clearInitFilters = _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter];
                        if (!clearInitFilters.Contains(column.Name))
                        {
                            clearInitFilters = StringValues.Concat(clearInitFilters, column.Name);
                            _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter] = clearInitFilters;
                        }
                    }
                    else
                    {
                        _query.Add(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter, column.Name);
                    }
                }
            }
            else
            {
                StringValues clearInitFilters = new StringValues();

                var columnsToAdd = Columns.Where(r => r.InitialFilterSettings != ColumnFilterValue.Null);
                foreach (var columnToAdd in columnsToAdd)
                {
                    clearInitFilters = StringValues.Concat(clearInitFilters, columnToAdd.Name);
                }

                if (_query.ContainsKey(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter))
                {
                    _query[QueryStringFilterSettings.DefaultClearInitFilterQueryParameter] = clearInitFilters;
                }
                else
                {
                    _query.Add(QueryStringFilterSettings.DefaultClearInitFilterQueryParameter, clearInitFilters);
                }
            }
        }
        /// <inheritdoc/>
        public override ValueTask ApplyAsync(RequestTransformContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var existingValues = TakeHeader(context, HeaderName);

            if (Append)
            {
                var values = StringValues.Concat(existingValues, Value);
                AddHeader(context, HeaderName, values);
            }
            else
            {
                // Set
                AddHeader(context, HeaderName, Value);
            }

            return(default);
Exemplo n.º 5
0
        public void Append(string key, string value)
        {
            if (_dictionary == null)
            {
                _dictionary = new Dictionary <string, StringValues>(0, StringComparer.OrdinalIgnoreCase);
            }

            if (_dictionary.TryGetValue(key, out var values))
            {
                if (values.FirstOrDefault(x => x == value) == null)
                {
                    _dictionary[key] = StringValues.Concat(values, value);
                    ValueCount++;
                }
            }
            else
            {
                _dictionary.Add(key, new StringValues(value));
                ValueCount++;
            }
        }
Exemplo n.º 6
0
        public static void AppendHeaderUnmodified(IHeaderDictionary headers, string key, StringValues values)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

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

            if (values.Count == 0)
            {
                return;
            }

            var existing = GetHeaderUnmodified(headers, key);

            SetHeaderUnmodified(headers, key, StringValues.Concat(existing, values));
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
    /// <inheritdoc />
    public void Append(ReadOnlySpan <KeyValuePair <string, string> > keyValuePairs, 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 <IServiceProvidersFeature>()?.RequestServices;
                _logger = services?.GetService <ILogger <ResponseCookies> >();
            }

            if (_logger != null)
            {
                foreach (var keyValuePair in keyValuePairs)
                {
                    Log.SameSiteCookieNotSecure(_logger, keyValuePair.Key);
                }
            }
        }

        var cookieSuffix = options.CreateCookieHeader(string.Empty, string.Empty).ToString()[1..];
        var cookies      = new string[keyValuePairs.Length];
        var position     = 0;

        foreach (var keyValuePair in keyValuePairs)
        {
            var key = _enableCookieNameEncoding ? Uri.EscapeDataString(keyValuePair.Key) : keyValuePair.Key;
            cookies[position] = string.Concat(key, "=", Uri.EscapeDataString(keyValuePair.Value), cookieSuffix);
            position++;
        }

        // Can't use += as StringValues does not override operator+
        // and the implict conversions will cause an incorrect string concat https://github.com/dotnet/runtime/issues/52507
        Headers.SetCookie = StringValues.Concat(Headers.SetCookie, cookies);
    }
Exemplo n.º 9
0
    /// <summary>
    /// Checks if the response should be compressed and sets the response headers.
    /// </summary>
    /// <returns>The compression provider to use if compression is enabled, otherwise null.</returns>
    private ICompressionProvider?InitializeCompressionHeaders()
    {
        if (_provider.ShouldCompressResponse(_context))
        {
            var headers = _context.Response.Headers;
            // If the MIME type indicates that the response could be compressed, caches will need to vary by the Accept-Encoding header
            var varyValues           = headers.GetCommaSeparatedValues(HeaderNames.Vary);
            var varyByAcceptEncoding = false;

            for (var i = 0; i < varyValues.Length; i++)
            {
                if (string.Equals(varyValues[i], HeaderNames.AcceptEncoding, StringComparison.OrdinalIgnoreCase))
                {
                    varyByAcceptEncoding = true;
                    break;
                }
            }

            if (!varyByAcceptEncoding)
            {
                // Can't use += as StringValues does not override operator+
                // and the implict conversions will cause an incorrect string concat https://github.com/dotnet/runtime/issues/52507
                headers.Vary = StringValues.Concat(headers.Vary, HeaderNames.AcceptEncoding);
            }

            var compressionProvider = ResolveCompressionProvider();
            if (compressionProvider != null)
            {
                // Can't use += as StringValues does not override operator+
                // and the implict conversions will cause an incorrect string concat https://github.com/dotnet/runtime/issues/52507
                headers.ContentEncoding = StringValues.Concat(headers.ContentEncoding, compressionProvider.EncodingName);
                headers.ContentMD5      = default; // Reset the MD5 because the content changed.
                headers.ContentLength   = default;
            }

            return(compressionProvider);
        }

        return(null);
    }
Exemplo n.º 10
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,
            };

            var cookieValue = setCookieHeaderValue.ToString();

            Headers[HeaderNames.SetCookie] = StringValues.Concat(Headers[HeaderNames.SetCookie], cookieValue);
        }
Exemplo n.º 11
0
        static void CopyHeaders(IHeaderDictionary responseHeaders, IEnumerable <KeyValuePair <string, IEnumerable <string> > > replyHeaders)
        {
            foreach (var replyHeader in replyHeaders)
            {
                var headerValue = default(StringValues);
                var isFirst     = true;
                foreach (var value in replyHeader.Value)
                {
                    if (isFirst)
                    {
                        headerValue = value;
                        isFirst     = false;
                    }
                    else
                    {
                        headerValue = StringValues.Concat(headerValue, value);
                    }
                }

                responseHeaders[replyHeader.Key] = headerValue;
            }
        }
        // Assumes the response status code has been set on the HttpContext already.
        /// <inheritdoc/>
        public override ValueTask ApplyAsync(ResponseTrailersTransformContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (Always || Success(context))
            {
                var existingHeader = TakeHeader(context, HeaderName);
                if (Append)
                {
                    var value = StringValues.Concat(existingHeader, Value);
                    SetHeader(context, HeaderName, value);
                }
                else
                {
                    SetHeader(context, HeaderName, Value);
                }
            }

            return(default);
Exemplo n.º 13
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);
    }
Exemplo n.º 14
0
        public async Task InvokeAsync(HttpContext context,
                                      IServiceProvider provider, IHostingEnvironment hostingEnvironment)
        {
            if (!context.Request.Path.StartsWithSegments(new PathString("/swagger")))
            {
                var scopeProperties = provider.GetRequiredService(typeof(ScopeProperties)) as ScopeProperties;

                context.Request.Headers.TryGetValue("X-ClientTrace", out StringValues clientTraceEntries);

                if (!StringValues.IsNullOrEmpty(clientTraceEntries))
                {
                    clientTraceEntries = StringValues.Concat(clientTraceEntries, hostingEnvironment.ApplicationName);
                }
                else
                {
                    clientTraceEntries = new StringValues(hostingEnvironment.ApplicationName);
                }

                scopeProperties.OtherProperties.Add("X-ClientTrace", clientTraceEntries);
            }
            await _next(context);
        }
Exemplo n.º 15
0
        private static void RestoreUpgradeHeaders(HttpContext context, HttpResponseMessage response)
        {
            if (response.Headers.TryGetValues(HeaderNames.Connection, out var connectionValues) &&
                response.Headers.TryGetValues(HeaderNames.Upgrade, out var upgradeValues))
            {
                var upgradeStringValues = StringValues.Empty;
                foreach (var value in upgradeValues)
                {
                    upgradeStringValues = StringValues.Concat(upgradeStringValues, value);
                }
                context.Response.Headers.TryAdd(HeaderNames.Upgrade, upgradeStringValues);

                foreach (var value in connectionValues)
                {
                    if (value.Equals("upgrade", StringComparison.OrdinalIgnoreCase))
                    {
                        context.Response.Headers.TryAdd(HeaderNames.Connection, value);
                        break;
                    }
                }
            }
        }
Exemplo n.º 16
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);
        }
        /// <inheritdoc/>
        public override Task ApplyAsync(RequestTransformContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var existingValues = TakeHeader(context, HeaderName);

            if (Append)
            {
                var values = StringValues.Concat(existingValues, Value);
                AddHeader(context, HeaderName, values);
            }
            else if (!string.IsNullOrEmpty(Value))
            {
                // Set
                AddHeader(context, HeaderName, Value);
            }

            return(Task.CompletedTask);
        }
        // Assumes the response status code has been set on the HttpContext already.
        /// <inheritdoc/>
        public override ValueTask ApplyAsync(ResponseTrailersTransformContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (Always || Success(context))
            {
                var existingHeader = TakeHeader(context, HeaderName);
                if (Append)
                {
                    var value = StringValues.Concat(existingHeader, Value);
                    SetHeader(context, HeaderName, value);
                }
                else if (!string.IsNullOrEmpty(Value))
                {
                    SetHeader(context, HeaderName, Value);
                }
                // If the given value is empty, any existing header is removed.
            }

            return(default);
        /// <inheritdoc/>
        public override StringValues Apply(HttpContext context, HttpRequestMessage proxyRequest, StringValues values)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var builder = new StringBuilder();

            AppendProto(context, builder);
            AppendHost(context, builder);
            AppendFor(context, builder);
            AppendBy(context, builder);
            var value = builder.ToString();

            if (Append)
            {
                return(StringValues.Concat(values, value));
            }

            // Set
            return(value);
        }
Exemplo n.º 20
0
        public static Dictionary <string, StringValues> ParseQueryString(QueryString queryString)
        {
            var state = new Dictionary <string, StringValues>();

            if (queryString == QueryString.Empty || queryString == s_almostEmpty)
            {
                return(state);
            }

            var qs = queryString.Value;

            if (qs[0] == '?')
            {
                qs = qs.Substring(1);
            }

            foreach (var pair in qs.Split('&'))
            {
                var parts = pair.Split(s_delimiter, 2);
                var key   = Uri.UnescapeDataString(parts[0].Replace('+', ' '));

                state.TryGetValue(key, out var values);

                if (parts.Length == 1)
                {
                    state[key] = values;
                }
                else
                {
                    var value = Uri.UnescapeDataString(parts[1].Replace('+', ' '));

                    state[key] = StringValues.Concat(value, values);
                }
            }

            return(state);
        }
        /// <inheritdoc/>
        public override Task ApplyAsync(RequestTransformContext context)
        {
            if (context is null)
            {
                throw new System.ArgumentNullException(nameof(context));
            }

            var existingValues = TakeHeader(context, HeaderName);

            var scheme = context.HttpContext.Request.Scheme;

            if (Append)
            {
                var values = StringValues.Concat(existingValues, scheme);
                AddHeader(context, HeaderName, values);
            }
            else
            {
                // Set
                AddHeader(context, HeaderName, scheme);
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 22
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);
        }
Exemplo n.º 23
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);
        }
Exemplo n.º 24
0
        public async Task InvokeAsync(HttpContext context)
        {
            if (!context.Request.Path.Equals(Options.Route, StringComparison.OrdinalIgnoreCase))
            {
                await Next(context);

                return;
            }

            if (!HttpMethods.IsPost(context.Request.Method))
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }



            context.Request.Query.TryGetValue("action", out var action);

            switch (action.ToString().ToLower())
            {
                #region 检查已经上传的分片数量
            case "chunks":
                var checker = context.RequestServices.GetService <ICheckChunksProcessor>();
                if (checker == null)
                {
                    await context.Response.WriteResponseAsync(HttpStatusCode.NotFound, "Not Found!");

                    break;
                }
                var checkResult = await checker.Process(context.Request.Query, context.Request.HasFormContentType?context.Request.Form : null, context.Request.Headers, context.Request);

                await context.Response.WriteResponseAsync(checkResult.StatusCode, checkResult.ErrorMsg, checkResult.Content, checkResult.Headers);

                break;
                #endregion

                #region 检查分片完整性
            case "chunk":
                var chunkChecker = context.RequestServices.GetService <ICheckChunkProcessor>();
                if (chunkChecker == null)
                {
                    await context.Response.WriteResponseAsync(HttpStatusCode.NotFound, "Not Found!");

                    break;
                }
                var chunkCheckResult = await chunkChecker.Process(context.Request.Query, context.Request.HasFormContentType?context.Request.Form : null, context.Request.Headers, context.Request);

                await context.Response.WriteResponseAsync(chunkCheckResult.StatusCode, chunkCheckResult.ErrorMsg, chunkCheckResult.Content, chunkCheckResult.Headers);

                break;
                #endregion

                #region 合并分片
            case "merge":
                var merger = context.RequestServices.GetService <IMergeProcessor>();
                if (merger == null)
                {
                    await context.Response.WriteResponseAsync(HttpStatusCode.NotFound, "Not Found!");

                    break;
                }
                try
                {
                    var merge = await merger.Process(context.Request.Query, context.Request.HasFormContentType?context.Request.Form : null, context.Request.Headers, context.Request);

                    if (!merge.Success)
                    {
                        await context.Response.WriteResponseAsync(HttpStatusCode.BadRequest, merge.ErrorMsg);

                        return;
                    }
                    var mergeHandler = context.RequestServices.GetRequiredService <IMergeHandler>();
                    var mergerResult = await mergeHandler.OnCompleted(context.Request.Query, context.Request.HasFormContentType?context.Request.Form : null, context.Request.Headers, merge.FileName);

                    await context.Response.WriteResponseAsync(mergerResult.StatusCode, mergerResult.ErrorMsg, mergerResult.Content, mergerResult.Headers);
                }
                catch (Exception e)
                {
                    await context.Response.WriteResponseAsync(HttpStatusCode.BadRequest, e.Message);
                }
                break;
                #endregion

                #region
            default:
                try
                {
                    if (!MediaTypeHeaderValue.TryParse(context.Request.ContentType, out var contentType))
                    {
                        await context.Response.WriteResponseAsync(HttpStatusCode.UnsupportedMediaType, "ContentType must be multipart/form-data.");

                        return;
                    }
                    if (!contentType.MediaType.Equals("multipart/form-data", StringComparison.OrdinalIgnoreCase))
                    {
                        await context.Response.WriteResponseAsync(HttpStatusCode.UnsupportedMediaType, "ContentType must be multipart/form-data.");

                        return;
                    }
                    var processor = context.RequestServices.GetRequiredService <IUploadProcessor>();
                    var boundary  = context.Request.GetMultipartBoundary();
                    var reader    = new MultipartReader(boundary, context.Request.Body);
                    var section   = await reader.ReadNextSectionAsync();

                    var formDic    = new Dictionary <string, StringValues>();
                    var fileResult = new List <UploadFileResult>();
                    while (section != null)
                    {
                        var header = section.GetContentDispositionHeader();
                        if (header != null)
                        {
                            if (header.FileName.HasValue || header.FileNameStar.HasValue)
                            {
                                var fileSection   = section.AsFileSection();
                                var extensionName = Path.GetExtension(fileSection.FileName);
                                var(success, uploadResult, errorMessage) = await processor.Process(context.Request.Query, new FormCollection(formDic), context.Request.Headers, fileSection.FileStream, extensionName, fileSection.FileName, fileSection.Name, context.Request);

                                if (!success)
                                {
                                    await context.Response.WriteResponseAsync(HttpStatusCode.BadRequest, errorMessage);

                                    return;
                                }

                                fileResult.Add(uploadResult);
                            }
                            else
                            {
                                var formSection = section.AsFormDataSection();
                                var value       = new StringValues(await formSection.GetValueAsync());
                                if (formDic.TryGetValue(formSection.Name, out var oldValue))
                                {
                                    formDic[formSection.Name] = StringValues.Concat(oldValue, value);
                                }
                                else
                                {
                                    formDic[formSection.Name] = value;
                                }
                            }
                        }
                        section = await reader.ReadNextSectionAsync();
                    }


                    if (!fileResult.Any())
                    {
                        await context.Response.WriteResponseAsync(HttpStatusCode.BadRequest, "未发现上传文件");

                        return;
                    }

                    var completeHandler = context.RequestServices.GetRequiredService <IUploadCompletedHandler>();
                    var result          = await completeHandler.OnCompleted(context.Request.Query, new FormCollection(formDic), context.Request.Headers, fileResult);

                    await context.Response.WriteResponseAsync(result.StatusCode, result.ErrorMsg, result.Content, result.Headers);
                }
                catch (Exception e)
                {
                    await context.Response.WriteResponseAsync(HttpStatusCode.BadRequest, e.Message);

                    Logger.LogError(e, "An exception occurred while uploading the middleware.");
                }
                break;
                #endregion
            }
        }
        /// <summary>
        /// Add to IfNoneMatch values.
        /// </summary>
        /// <returns>The IfNoneMatch values.</returns>
        public static void AddIfNoneMatch(this IHeaderDictionary headers, EntityTagHeaderValue value)
        {
            StringValues newValue = StringValues.Concat(headers["If-None-Match"], new StringValues(value.ToString()));

            headers["If-None-Match"] = newValue;
        }
Exemplo n.º 26
0
 protected static StringValues AppendValue(StringValues existing, string append)
 {
     return(StringValues.Concat(existing, append));
 }
Exemplo n.º 27
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);
            }
        }
        public async Task When_uploading_a_file_that_is_a_zip()
        {
            var client    = new MemoryBlobClient();
            var store     = new InMemoryStreamStore();
            var validator = new ZipArchiveValidator(Encoding.UTF8);
            var resolver  = Resolve.WhenEqualToMessage(
                new RoadNetworkChangesArchiveCommandModule(
                    client,
                    store,
                    new FakeRoadNetworkSnapshotReader(),
                    validator,
                    SystemClock.Instance
                    )
                );
            var controller = new UploadController(Dispatch.Using(resolver),
                                                  client)
            {
                ControllerContext = new ControllerContext {
                    HttpContext = new DefaultHttpContext()
                }
            };

            using (var sourceStream = new MemoryStream())
            {
                using (var archive = new ZipArchive(sourceStream, ZipArchiveMode.Create, true, Encoding.UTF8))
                {
                    var entry = archive.CreateEntry("entry");
                    using (var entryStream = entry.Open())
                    {
                        entryStream.Write(new byte[] { 1, 2, 3, 4 });
                        entryStream.Flush();
                    }
                }

                sourceStream.Position = 0;

                var formFile = new FormFile(sourceStream, 0L, sourceStream.Length, "name", "name")
                {
                    Headers = new HeaderDictionary(new Dictionary <string, StringValues>
                    {
                        { "Content-Type", StringValues.Concat(StringValues.Empty, "application/zip") }
                    })
                };
                var result = await controller.Post(formFile);

                Assert.IsType <OkResult>(result);

                var page = await store.ReadAllForwards(Position.Start, 1, true);

                var message = Assert.Single(page.Messages);
                Assert.Equal(nameof(Messages.RoadNetworkChangesArchiveUploaded), message.Type);
                var uploaded =
                    JsonConvert.DeserializeObject <Messages.RoadNetworkChangesArchiveUploaded>(
                        await message.GetJsonData());

                Assert.True(await client.BlobExistsAsync(new BlobName(uploaded.ArchiveId)));
                var blob = await client.GetBlobAsync(new BlobName(uploaded.ArchiveId));

                using (var openStream = await blob.OpenAsync())
                {
                    var resultStream = new MemoryStream();
                    openStream.CopyTo(resultStream);
                    resultStream.Position = 0;
                    sourceStream.Position = 0;
                    Assert.Equal(sourceStream.ToArray(), resultStream.ToArray());
                }
            }
        }