public RPCMiddlewareTest()
        {
            this.authorization   = new Mock <IRPCAuthorization>();
            this.delegateContext = new Mock <RequestDelegate>();

            this.httpContext       = new DefaultHttpContext();
            this.response          = new HttpResponseFeature();
            this.request           = new HttpRequestFeature();
            this.response.Body     = new MemoryStream();
            this.featureCollection = new FeatureCollection();

            this.httpContextFactory = new Mock <IHttpContextFactory>();
            this.httpContextFactory.Setup(f => f.Create(It.IsAny <FeatureCollection>())).Returns((FeatureCollection f) => {
                DefaultHttpContext newHttpContext = new DefaultHttpContext();
                newHttpContext.Initialize(f);

                return(newHttpContext);
            });

            var nodeSettings = new NodeSettings(new StratisRegTest());

            this.rpcSettings = new RpcSettings(nodeSettings);

            this.middleware = new RPCMiddleware(this.delegateContext.Object, this.authorization.Object, this.LoggerFactory.Object, this.httpContextFactory.Object, new DataFolder(string.Empty), this.rpcSettings);
        }
Exemplo n.º 2
0
        async Task <HttpRequestFeature> CreateRequestAsync(Stream stream, CancellationToken cancellationToken)
        {
            var firstLine = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);

            var parts  = firstLine.Split(' ');
            var result = new HttpRequestFeature();

            result.Method = parts[0];
            var uri = new Uri(parts[1], UriKind.RelativeOrAbsolute);

            if (!uri.IsAbsoluteUri)
            {
                uri = new Uri(_localhostUri, uri);
            }
            result.Protocol = parts[2];
            for (; ;)
            {
                var line = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                if (line.Length == 0)
                {
                    break;
                }
                (var name, var values) = HttpParser.ParseHeaderNameValues(line);
                result.Headers.Add(name, new Microsoft.Extensions.Primitives.StringValues(values.ToArray()));
            }
            result.Scheme      = uri.Scheme;
            result.Path        = PathString.FromUriComponent(uri);
            result.QueryString = QueryString.FromUriComponent(uri).Value;
            result.Body        = new BodyStream(stream, result.Headers.ContentLength);
            return(result);
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="areaName">The name of the area containing the Emails view folder if applicable</param>
        /// <returns></returns>
#if ASPNET5
        ActionContext CreateControllerContext(string areaName, IHttpRequestFeature requsetFeature)
        {
            var routeData = new Microsoft.AspNetCore.Routing.RouteData();

            routeData.Values["controller"] = EmailViewDirectoryName;

            // if populated will add searching the named Area for the view
            if (!string.IsNullOrWhiteSpace(areaName))
            {
                routeData.DataTokens["Area"] = areaName;
            }

            var actionDescriptor = new ActionDescriptor();

            actionDescriptor.RouteValues = routeData.Values.ToDictionary(kv => kv.Key, kv => kv.Value.ToString());
            FeatureCollection featureCollection = new FeatureCollection();
            var requsetFeature_local            = new HttpRequestFeature();

            requsetFeature_local.Method   = "GET";
            requsetFeature_local.Protocol = requsetFeature?.Protocol;
            requsetFeature_local.PathBase = requsetFeature?.PathBase;
            requsetFeature_local.Scheme   = requsetFeature?.Scheme;
            featureCollection.Set <IHttpRequestFeature>(requsetFeature_local);
            featureCollection.Set <IHttpResponseFeature>(new HttpResponseFeature());
            var httpContext = new DefaultHttpContext(featureCollection);

            httpContext.RequestServices = serviceProvider;
            var actionContext = new ActionContext(httpContext, routeData, actionDescriptor);

            actionContext.RouteData = routeData;

            return(actionContext);
        }
Exemplo n.º 4
0
        public void RouteAsyncLoadsRouteContextOntoRouteData()
        {
            var request = new HttpRequestFeature();

            SetupRequestBody(request, "{\"method\": \"GET\"}");
            var          context  = new RouteContext(this.PrepareDefaultHttpContext(request));
            RouteContext callback = null;

            this.inner.Setup(i => i.RouteAsync(It.IsAny <RouteContext>()))
            .Callback <RouteContext>((r) => { callback = r; })
            .Returns(Task.FromResult(0));
            var desciptors = new ActionDescriptorCollection(new List <ControllerActionDescriptor>
            {
                new ControllerActionDescriptor
                {
                    ActionName     = "GET",
                    ControllerName = "RPCController"
                }
            }, 1);

            this.actionDescriptor.Setup(a => a.ActionDescriptors)
            .Returns(desciptors);

            Task task = this.handler.RouteAsync(context);

            task.Wait();

            Assert.Equal("GET", callback.RouteData.Values["action"]);
            Assert.Equal("RPCController", callback.RouteData.Values["controller"]);
            Assert.True(callback.RouteData.Values["req"].GetType() == typeof(JObject));
        }
Exemplo n.º 5
0
 private static void SetupRequestBody(HttpRequestFeature request, string requestBody)
 {
     request.Body = new MemoryStream();
     byte[] bytes = Encoding.ASCII.GetBytes(requestBody);
     request.Body.Write(bytes, 0, bytes.Length);
     request.Body.Position = 0;
 }
Exemplo n.º 6
0
        public ViewRenderService(
            IHttpContextAccessor httpContextAccessor,
            IRazorViewEngine razorViewEngine,
            ITempDataProvider tempDataProvider,
            IServiceProvider serviceProvider,
            IConfiguration configuration)
        {
            _httpContext      = httpContextAccessor.HttpContext;
            _razorViewEngine  = razorViewEngine;
            _tempDataProvider = tempDataProvider;
            _serviceProvider  = serviceProvider;
            _configuration    = configuration;

            var emailBaseUrl = _configuration.GetSection("Email:BaseUrl").Get <string>();
            var url          = new Uri(emailBaseUrl);

            _cultureInfo = CultureInfo.GetCultureInfo("en-NZ");

            _defaultRequestFeature = new HttpRequestFeature
            {
                Headers =
                {
                    { HeaderNames.Host,           url.Authority },
                    { HeaderNames.AcceptLanguage, "en-NZ"       },
                },
                Scheme      = url.Scheme,
                QueryString = url.Query,
                Path        = url.AbsolutePath,
            };
        }
Exemplo n.º 7
0
        public void TestNegotiateHandlerWithMultipleEndpointsAndCustomRouter()
        {
            var config          = new ConfigurationBuilder().Build();
            var router          = new TestCustomRouter(ConnectionString3);
            var serviceProvider = new ServiceCollection().AddSignalR()
                                  .AddAzureSignalR(
                o => o.Endpoints = new ServiceEndpoint[]
            {
                new ServiceEndpoint(ConnectionString2),
                new ServiceEndpoint(ConnectionString3),
                new ServiceEndpoint(ConnectionString4),
            })
                                  .Services
                                  .AddLogging()
                                  .AddSingleton <IEndpointRouter>(router)
                                  .AddSingleton <IConfiguration>(config)
                                  .BuildServiceProvider();

            var requestFeature = new HttpRequestFeature
            {
                Path = "/user/path/negotiate/",
            };

            var features = new FeatureCollection();

            features.Set <IHttpRequestFeature>(requestFeature);
            var httpContext = new DefaultHttpContext(features);

            var handler           = serviceProvider.GetRequiredService <NegotiateHandler>();
            var negotiateResponse = handler.Process(httpContext, "chat");

            Assert.NotNull(negotiateResponse);
            Assert.Equal($"http://localhost3/client/?hub=chat&asrs.op=%2Fuser%2Fpath", negotiateResponse.Url);
        }
Exemplo n.º 8
0
        public async Task TestNegotiateHandlerResponseContainsValidMaxPollInterval(int maxPollInterval)
        {
            var config          = new ConfigurationBuilder().Build();
            var serviceProvider = new ServiceCollection().AddSignalR()
                                  .AddAzureSignalR(o =>
            {
                o.ConnectionString         = DefaultConnectionString;
                o.MaxPollIntervalInSeconds = maxPollInterval;
            })
                                  .Services
                                  .AddLogging()
                                  .AddSingleton <IConfiguration>(config)
                                  .BuildServiceProvider();

            var requestFeature = new HttpRequestFeature
            {
                Path        = "/user/path/negotiate/",
                QueryString = "?endpoint=chosen"
            };
            var responseFeature = new HttpResponseFeature();
            var features        = new FeatureCollection();

            features.Set <IHttpRequestFeature>(requestFeature);
            features.Set <IHttpResponseFeature>(responseFeature);
            var httpContext = new DefaultHttpContext(features);

            var handler  = serviceProvider.GetRequiredService <NegotiateHandler>();
            var response = await handler.Process(httpContext, "chat");

            Assert.Equal(200, responseFeature.StatusCode);

            var tokens = JwtTokenHelper.JwtHandler.ReadJwtToken(response.AccessToken);

            Assert.Contains(tokens.Claims, x => x.Type == Constants.ClaimType.MaxPollInterval && x.Value == maxPollInterval.ToString());
        }
        async Task <HttpRequestFeature> CreateRequesteAsync(Stream stream)
        {
            var lineReader  = new ByLineReader(stream, 1024);
            var requestLine = await lineReader.NextLineAsync().ConfigureAwait(false);

            var firstLine = HttpParser.GetAsciiString(requestLine);
            var parts     = firstLine.Split(' ');
            var result    = new HttpRequestFeature();

            result.Method = parts[0];
            var uri = new Uri("http://localhost" + parts[1]);

            result.Protocol = parts[2];
            for (; ;)
            {
                var line = await lineReader.NextLineAsync().ConfigureAwait(false);

                if (line.Count == 0)
                {
                    break;
                }
                (var name, var values) = HttpParser.ParseHeaderNameValue(line);
                result.Headers.Add(name, new Microsoft.Extensions.Primitives.StringValues(values.ToArray()));
            }
            result.Scheme      = uri.Scheme;
            result.Path        = PathString.FromUriComponent(uri);
            result.QueryString = QueryString.FromUriComponent(uri).Value;
            result.Body        = new StreamWithPrefix(lineReader.Remaining, stream, result.Headers.ContentLength);
            return(result);
        }
Exemplo n.º 10
0
        public void GenerateNegotiateResponseWithPathAndQuery(string path, string queryString, string expectedQueryString)
        {
            var config          = new ConfigurationBuilder().Build();
            var serviceProvider = new ServiceCollection().AddSignalR()
                                  .AddAzureSignalR(o => o.ConnectionString = DefaultConnectionString)
                                  .Services
                                  .AddLogging()
                                  .AddSingleton <IConfiguration>(config)
                                  .BuildServiceProvider();

            var requestFeature = new HttpRequestFeature
            {
                Path        = path,
                QueryString = queryString
            };
            var features = new FeatureCollection();

            features.Set <IHttpRequestFeature>(requestFeature);
            var httpContext = new DefaultHttpContext(features);

            var handler           = serviceProvider.GetRequiredService <NegotiateHandler>();
            var negotiateResponse = handler.Process(httpContext, "chat");

            Assert.NotNull(negotiateResponse);
            Assert.EndsWith($"?hub=chat&{expectedQueryString}", negotiateResponse.Url);
        }
Exemplo n.º 11
0
            public void Configure(IApplicationBuilder app)
            {
                app.UseDeveloperExceptionPage();
                app.Run(context =>
                {
                    var server = context.RequestServices.GetRequiredService <IServer>();
                    var gate   = server.Features.Get <RequestGate>();

                    var feature     = context.Features.Get <IHttpRequestFeature>();
                    var mockRequest = new HttpRequestFeature
                    {
                        Scheme      = feature.Scheme,
                        RawTarget   = feature.RawTarget,
                        Protocol    = feature.Protocol,
                        Method      = feature.Method,
                        Path        = feature.Path,
                        PathBase    = feature.PathBase,
                        QueryString = feature.QueryString,
                        Headers     = feature.Headers,
                        Body        = new MemoryStream()
                    };
                    feature.Body.CopyTo(mockRequest.Body, 1024);
                    mockRequest.Body.Seek(0, SeekOrigin.Begin);

                    gate.Request = mockRequest;

                    context.Response.StatusCode = (int)HttpStatusCode.OK;
                    return(Task.CompletedTask);
                });
            }
Exemplo n.º 12
0
        public async Task AbortNonSuccessStatusCode()
        {
            var requestFeature = new HttpRequestFeature {
                Path = "/api/batch"
            };

            requestFeature.Headers.Add(HeaderNames.ContentType,
                                       "multipart/mixed; boundary=\"batch_357647d1-a6b5-4e6a-aa73-edfc88d8866e\"");
            requestFeature.Body = TestUtilities.GetNormalizedContentStream("MultipartRequest.txt");
            var responseFeature = new HttpResponseFeature();
            var mockedEvents    = new MockedBatchEventHandler();

            using (responseFeature.Body = new MemoryStream())
            {
                await AssertExecution(requestFeature, responseFeature, mockedEvents,
                                      CreateFirstResponse(),
                                      CreateInternalServerResponse(),
                                      CreateThirdResponse(),
                                      CreateFourthResponse()).ConfigureAwait(false);

                Assert.Equal(StatusCodes.Status500InternalServerError, responseFeature.StatusCode);
                Assert.Equal(1, mockedEvents.BatchEndCount);
                Assert.Equal(1, mockedEvents.BatchStartCount);
                Assert.Equal(2, mockedEvents.BatchRequestPreparationCount);
                Assert.Equal(2, mockedEvents.BatchRequestExecutingCount);
                Assert.Equal(2, mockedEvents.BatchRequestExecutedCount);
            }
        }
Exemplo n.º 13
0
        public void GenerateNegotiateResponseWithAppName(string appName, string expectedResponse)
        {
            var config          = new ConfigurationBuilder().Build();
            var serviceProvider = new ServiceCollection().AddSignalR()
                                  .AddAzureSignalR(o =>
            {
                o.ConnectionString = DefaultConnectionString;
                o.ApplicationName  = appName;
            })
                                  .Services
                                  .AddLogging()
                                  .AddSingleton <IConfiguration>(config)
                                  .BuildServiceProvider();

            var requestFeature = new HttpRequestFeature
            {
            };
            var features = new FeatureCollection();

            features.Set <IHttpRequestFeature>(requestFeature);
            var httpContext = new DefaultHttpContext(features);

            var handler           = serviceProvider.GetRequiredService <NegotiateHandler>();
            var negotiateResponse = handler.Process(httpContext, "chat");

            Assert.NotNull(negotiateResponse);
            Assert.EndsWith(expectedResponse, negotiateResponse.Url);
        }
Exemplo n.º 14
0
        private static FeatureCollection BuildFeatureCollection(HttpRequestFeature requestFeature, HttpResponseFeature responseFeature)
        {
            var features = new FeatureCollection();

            features.Set <IHttpRequestFeature>(requestFeature);
            features.Set <IHttpResponseFeature>(responseFeature);
            return(features);
        }
Exemplo n.º 15
0
        public HttpContext Execute(HttpRequestFeature requestFeature,
                                   Action <FeatureCollection> featureCollectionAction = null)
        {
            var task = ExecuteAsync(requestFeature, featureCollectionAction);

            task.Wait();
            return(task.Result);
        }
Exemplo n.º 16
0
                public override async Task HandleBasicDeliver(String consumerTag, UInt64 deliveryTag, Boolean redelivered, String exchange, String routingKey, IBasicProperties properties, Byte[] body)
                {
                    var app = _server._application;

                    var path = String.Empty;

                    if (properties.Headers.TryGetValue("path", out var pathObj))
                    {
                        path = Encoding.UTF8.GetString((Byte[])pathObj);
                        if (!path.StartsWith("/"))
                        {
                            path = "/" + path;
                        }
                    }


                    var requestFeature = new HttpRequestFeature
                    {
                        Body     = new MemoryStream(body, writable: false),
                        Method   = "GET",
                        Protocol = "http",
                        Path     = path,
                        Scheme   = "http",
                    };

                    var responseBodyStream = new MemoryStream();
                    var responseFeature    = new HttpResponseFeature
                    {
                        Body = responseBodyStream,
                    };

                    var features = new FeatureCollection(_server._features);

                    features.Set <IHttpRequestFeature>(requestFeature);
                    features.Set <IHttpResponseFeature>(responseFeature);

                    var context = app.CreateContext(features);
                    await app.ProcessRequestAsync(context);

                    if (properties.IsReplyToPresent() && properties.ReplyToAddress != null)
                    {
                        var responseBody = responseBodyStream.ToArray();
                        var props        = Model.CreateBasicProperties();
                        if (props.Headers == null)
                        {
                            props.Headers = new Dictionary <String, Object>();
                        }
                        foreach (var header in responseFeature.Headers)
                        {
                            props.Headers.Add(header.Key, Encoding.UTF8.GetBytes(header.Value));
                        }
                        Model.BasicPublish(properties.ReplyToAddress, props, responseBody);
                    }

                    Model.BasicAck(deliveryTag, multiple: false);

                    app.DisposeContext(context, null);
                }
        /// <summary>
        /// Invokes batch request.
        /// </summary>
        /// <param name="httpContext">Source batch request context.</param>
        /// <param name="requests">Array of requests.</param>
        private async Task InvokeAsyncBatchAsync(HttpContext httpContext, JArray requests)
        {
            JArray responses = new JArray();

            foreach (JObject requestObj in requests)
            {
                var contextFeatures = new FeatureCollection(httpContext.Features);

                StringBuilder requestStringBuilder = new StringBuilder();
                await requestObj.WriteToAsync(new JsonTextWriter(new StringWriter(requestStringBuilder)));

                var requestFeature = new HttpRequestFeature()
                {
                    Body        = new MemoryStream(Encoding.UTF8.GetBytes(requestStringBuilder.ToString())),
                    Headers     = httpContext.Request.Headers,
                    Method      = httpContext.Request.Method,
                    Protocol    = httpContext.Request.Protocol,
                    Scheme      = httpContext.Request.Scheme,
                    QueryString = httpContext.Request.QueryString.Value
                };
                contextFeatures.Set <IHttpRequestFeature>(requestFeature);

                var responseMemoryStream = new MemoryStream();
                var responseFeature      = new HttpResponseFeature()
                {
                    Body = responseMemoryStream
                };
                contextFeatures.Set <IHttpResponseFeature>(responseFeature);

                contextFeatures.Set <IHttpRequestLifetimeFeature>(new HttpRequestLifetimeFeature());

                var context = this.httpContextFactory.Create(contextFeatures);

                try
                {
                    await this.next.Invoke(context).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    await this.HandleRpcInvokeExceptionAsync(context, ex);
                }

                responseMemoryStream.Position = 0;
                var response = (responseMemoryStream.Length == 0) ? CreateError(RPCErrorCode.RPC_METHOD_NOT_FOUND, "Method not found") : await JObject.LoadAsync(new JsonTextReader(new StreamReader(responseMemoryStream)));

                responses.Add(response);
            }

            // Update the response with the array of responses.
            using (StreamWriter streamWriter = new StreamWriter(httpContext.Response.Body))
                using (JsonTextWriter textWriter = new JsonTextWriter(streamWriter))
                {
                    await responses.WriteToAsync(textWriter);
                }
        }
Exemplo n.º 18
0
        private static IRequestCookieCollection MockRequestCookieCollection(string key, string value)
        {
            var requestFeature    = new HttpRequestFeature();
            var featureCollection = new FeatureCollection();

            requestFeature.Headers = new HeaderDictionary {
                { HeaderNames.Cookie, new StringValues(key + "=" + value) }
            };
            featureCollection.Set <IHttpRequestFeature>(requestFeature);
            var cookiesFeature = new RequestCookiesFeature(featureCollection);

            return(cookiesFeature.Cookies);
        }
Exemplo n.º 19
0
        public void EmptyKeysNotAddedToQueryCollection(string queryString)
        {
            var features = new FeatureCollection();
            var request = new HttpRequestFeature();
            request.QueryString = queryString;
            features[typeof(IHttpRequestFeature)] = request;

            var provider = new QueryFeature(features);

            var queryCollection = provider.Query;

            Assert.Equal(0, queryCollection.Count);
        }
Exemplo n.º 20
0
    public void EmptyKeysNotAddedToQueryCollection(string queryString)
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = queryString
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Equal(0, queryCollection.Count);
    }
Exemplo n.º 21
0
        public RPCMiddlewareTest()
        {
            this.httpContext     = new DefaultHttpContext();
            this.authorization   = new Mock <IRPCAuthorization>();
            this.delegateContext = new Mock <RequestDelegate>();

            this.httpContext       = new DefaultHttpContext();
            this.response          = new HttpResponseFeature();
            this.request           = new HttpRequestFeature();
            this.response.Body     = new MemoryStream();
            this.featureCollection = new FeatureCollection();

            this.middleware = new RPCMiddleware(this.delegateContext.Object, this.authorization.Object, this.LoggerFactory.Object);
        }
Exemplo n.º 22
0
        public void KeyWithoutValuesAddedToQueryCollection(string queryString, string emptyParam)
        {
            var features = new FeatureCollection();
            var request = new HttpRequestFeature();
            request.QueryString = queryString;
            features[typeof(IHttpRequestFeature)] = request;

            var provider = new QueryFeature(features);

            var queryCollection = provider.Query;

            Assert.True(queryCollection.Keys.Contains(emptyParam));
            Assert.Equal(string.Empty, queryCollection[emptyParam]);
        }
Exemplo n.º 23
0
    public void ParseEmptyOrNullQueryWorks(string queryString)
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = queryString
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Empty(queryCollection);
    }
Exemplo n.º 24
0
        private IHttpRequestFeature CreateHttpRequest(IMqRequestFeature mqRequest, IHeaderConverter headerConverter)
        {
            var props   = mqRequest.Properties;
            var headers = props?.Headers;

            var httpRequest = new HttpRequestFeature
            {
                Scheme   = "amqp",
                Protocol = _mqConnection.Connection.Protocol.ApiName,
            };

            httpRequest.PathBase = _pathBaseBase
                                   + "/" + (mqRequest.Exchange ?? String.Empty)
                                   + "/" + (mqRequest.RoutingKey ?? String.Empty);

            if (mqRequest.Body != null)
            {
                httpRequest.Body = new MemoryStream(mqRequest.Body, writable: false);
                httpRequest.Headers[HeaderNames.ContentLength] = mqRequest.Body.LongLength.ToString();
            }

            if (props != null)
            {
                // TODO: fill headers from props.
            }

            if (headers != null)
            {
                if (headers.TryGetValue(HeaderNames.Method, out var rawMethod))
                {
                    httpRequest.Method = headerConverter.ReadString(rawMethod);
                }
                if (headers.TryGetValue(HeaderNames.Path, out var rawPath))
                {
                    httpRequest.Path = headerConverter.ReadString(rawPath);
                }
                if (headers.TryGetValue(HeaderNames.QueryString, out var rawQueryString))
                {
                    httpRequest.QueryString = headerConverter.ReadString(rawQueryString);
                }

                foreach (var item in headers)
                {
                    httpRequest.Headers[item.Key] = headerConverter.Read(item.Value);
                }
            }

            return(httpRequest);
        }
Exemplo n.º 25
0
    public void KeyWithoutValuesAddedToQueryCollection(string queryString, string emptyParam)
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = queryString
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.True(queryCollection.Keys.Contains(emptyParam));
        Assert.Equal(string.Empty, queryCollection[emptyParam]);
    }
Exemplo n.º 26
0
    public void ParseQueryWithEncodedKeyEncodedValuesWorks()
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = "?fields+%5BtodoItems%5D=%5B+1+%5D&fields+%5BtodoItems%5D=%5B+2+%5D"
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Single(queryCollection);
        Assert.Equal(new[] { "[ 1 ]", "[ 2 ]" }, queryCollection["fields [todoItems]"]);
    }
Exemplo n.º 27
0
    public void ParseQueryWithEncodedKeyEmptyValueWorks()
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = "?fields+%5BtodoItems%5D="
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Single(queryCollection);
        Assert.Equal("", queryCollection["fields [todoItems]"].FirstOrDefault());
    }
Exemplo n.º 28
0
    public void ParseQueryWithEmptyKeyWorks()
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = "?=value1&="
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Single(queryCollection);
        Assert.Equal(new[] { "value1", "" }, queryCollection[""]);
    }
Exemplo n.º 29
0
    public void ParseQueryWithThreefoldKeysGroups()
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = "?key1=valueA&key2=valueB&key1=valueC&key1=valueD"
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Equal(2, queryCollection.Count);
        Assert.Equal(new[] { "valueA", "valueC", "valueD" }, queryCollection["key1"]);
        Assert.Equal("valueB", queryCollection["key2"].FirstOrDefault());
    }
Exemplo n.º 30
0
    public void CaseInsensitiveWithFewKeys()
    {
        // need to use less than 10 keys to test array storage code path
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = "?key=1&Key=2&key=3&Key=4&KEy=5"
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Equal(1, queryCollection.Count);
        Assert.Equal(new[] { "1", "2", "3", "4", "5" }, queryCollection["KEY"]);
    }
Exemplo n.º 31
0
    public void ParseQueryWithEmptyValuesWorks()
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = "?key1=&key2="
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Equal(2, queryCollection.Count);
        Assert.Equal(string.Empty, queryCollection["key1"].FirstOrDefault());
        Assert.Equal(string.Empty, queryCollection["key2"].FirstOrDefault());
    }
Exemplo n.º 32
0
    public void ParseQueryWithUniqueKeysWorks(string queryString)
    {
        var features = new FeatureCollection();

        features[typeof(IHttpRequestFeature)] = new HttpRequestFeature {
            QueryString = queryString
        };

        var provider = new QueryFeature(features);

        var queryCollection = provider.Query;

        Assert.Equal(2, queryCollection.Count);
        Assert.Equal("value1", queryCollection["key1"].FirstOrDefault());
        Assert.Equal("value2", queryCollection["key2"].FirstOrDefault());
    }
Exemplo n.º 33
0
        public void QueryReturnsParsedQueryCollection()
        {
            // Arrange
            var features = new FeatureCollection();
            var request = new HttpRequestFeature();
            request.QueryString = "foo=bar";
            features[typeof(IHttpRequestFeature)] = request;

            var provider = new QueryFeature(features);

            // Act
            var queryCollection = provider.Query;

            // Assert
            Assert.Equal("bar", queryCollection["foo"]);
        }