Exemple #1
0
        public RequestInfo(Verb method, HttpUrl url, Stream body, IClaimBasedIdentity identity, HeaderCollection headers)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            Method = method;
            Url = url;
            Body = new UnclosableStream(_stream = body);
            _identity = identity;
            Headers = headers ?? new HeaderCollection();
        }
Exemple #2
0
        private static IApiDocumentation GetApiDocumentation(HttpUrl url)
        {
            string contentType;
            var responseStream = new UnclosableStream(GetResponse(Method, url, out contentType));
            var container = UrsaConfigurationSection.InitializeComponentProvider();
            container.Register<IHttpServerConfiguration>(new StaticHttpServerConfiguration((Uri)url));
            var headers = new HeaderCollection();
            if (!String.IsNullOrEmpty(contentType))
            {
                ((IDictionary<string, string>)headers)[Header.Accept] = contentType;
                ((IDictionary<string, string>)headers)[Header.ContentType] = contentType;
            }

            var apiDocumentationId = url.WithFragment(String.Empty);
            var httpRequest = new RequestInfo(Verb.Parse(Method), apiDocumentationId, responseStream, new BasicClaimBasedIdentity(), headers);
            var converterProvider = container.Resolve<IConverterProvider>();
            var converter = converterProvider.FindBestInputConverter<IApiDocumentation>(httpRequest);
            if (converter == null)
            {
                throw new NotSupportedException(String.Format("Content type of '{0}' is not supported.", contentType));
            }

            converter.ConvertTo<IApiDocumentation>(httpRequest);
            return _container.Resolve<IEntityContext>().Load<IApiDocumentation>((Uri)apiDocumentationId);
        }
        public void it_should_remove_a_header()
        {
            HeaderCollection headers = new HeaderCollection();
            headers.Add(new Header("Header1", new[] { new HeaderValue("Value1", new HeaderParameter("Parameter1", "ParameterValue1")) }));
            headers.Remove("Header1");

            headers.Count.Should().Be(0);
        }
        public void it_should_serialize_the_headers_to_its_string_representation()
        {
            HeaderCollection headers = new HeaderCollection();
            headers.Add(new Header("Header1", new[] { new HeaderValue("Value1", new HeaderParameter("Parameter1", "ParameterValue1")) }));
            headers.Add(new Header("Header2", new[] { new HeaderValue("Value2", new HeaderParameter("Parameter2", "ParameterValue2")) }));

            string expected = String.Format("{0}\r\n{1}\r\n\r\n", headers["Header1"], headers["Header2"]);
            headers.ToString().Should().Be(expected);
        }
        public void it_should_set_a_header()
        {
            HeaderCollection headers = new HeaderCollection();
            headers.Set(new Header("Header1", new[] { new HeaderValue("Value1", new HeaderParameter("Parameter1", "ParameterValue1")) }));
            headers.Set(new Header("Header1", "Value2"));

            headers.Count.Should().Be(1);
            headers["Header1"].Values.Count.Should().Be(1);
            headers["Header1"].Values.First().Parameters.Count.Should().Be(0);
        }
        public void it_should_get_a_header_by_its_name()
        {
            HeaderCollection headers = new HeaderCollection();
            headers.Add(new Header("Header1", new[] { new HeaderValue("Value1", new HeaderParameter("Parameter1", "ParameterValue1")) }));

            Header header = headers["Header1"];

            header.Should().NotBeNull();
            header.Name.Should().Be("Header1");
        }
        public void it_should_add_a_header()
        {
            HeaderCollection headers = new HeaderCollection();
            headers.Add(new Header("Header1", new List<HeaderValue>(new[] { new HeaderValue("Value1", new HeaderParameter("Parameter1", "ParameterValue1")) })));
            headers.Add("Header1", "Value2");

            headers.Count.Should().Be(1);
            headers["Header1"].Values.Count.Should().Be(2);
            headers["Header1"].Values.First().Parameters.Count.Should().Be(1);
        }
Exemple #8
0
        /// <summary>Tries to parse a given string as a <see cref="HeaderCollection" />.</summary>
        /// <param name="headers">String to be parsed.</param>
        /// <param name="headersCollection">Resulting collection of headers if parsing was successful; otherwise <b>null</b>.</param>
        /// <returns><b>true</b> if the parsing was successful; otherwise <b>false</b>.</returns>
        public static bool TryParse(string headers, out HeaderCollection headersCollection)
        {
            bool result = false;
            headersCollection = null;
            try
            {
                headersCollection = Parse(headers);
                result = true;
            }
            catch
            {
            }

            return result;
        }
Exemple #9
0
        public ResponseInfo(Encoding encoding, RequestInfo request, HeaderCollection headers)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            Encoding = encoding;
            Request = request;
            _headers = headers ?? new HeaderCollection();
        }
Exemple #10
0
        public ResponseInfo(Encoding encoding, RequestInfo request, params Header[] headers)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            Encoding = encoding;
            Request = request;
            _headers = new HeaderCollection();
            headers.ForEach(header => _headers.Add(header));
        }
Exemple #11
0
 protected ObjectResponseInfo(Encoding encoding, RequestInfo request, HeaderCollection headers) : base(encoding, request, headers)
 {
 }
Exemple #12
0
        private async Task HandleRequest(IOwinContext context)
        {
            var headers = new HeaderCollection();
            context.Request.Headers.ForEach(header => headers[header.Key] = new Header(header.Key, header.Value));
            var requestInfo = new RequestInfo(
                Verb.Parse(context.Request.Method),
                (HttpUrl)UrlParser.Parse(context.Request.Uri.AbsoluteUri.TrimEnd('/')),
                context.Request.Body,
                new OwinPrincipal(context.Authentication.User),
                headers);
            System.Runtime.Remoting.Messaging.CallContext.HostContext = requestInfo;
            ResponseInfo response;
            try
            {
                response = await _requestHandler.HandleRequestAsync(requestInfo);
            }
            finally
            {
                System.Runtime.Remoting.Messaging.CallContext.HostContext = null;
            }

            if ((IsResponseNoMatchingRouteFoundException(response)) && (Next != null))
            {
                await Next.Invoke(context);
                return;
            }

            context.Response.StatusCode = (int)response.Status;
            foreach (var header in response.Headers)
            {
                switch (header.Name)
                {
                    case Header.ContentLength:
                        context.Response.ContentLength = response.Body.Length;
                        break;
                    default:
                        context.Response.Headers.Add(header.Name, header.Values.Select(headerValue => headerValue.ToString()).ToArray());
                        break;
                }
            }

            response.Body.CopyTo(context.Response.Body);
        }
Exemple #13
0
 protected ObjectResponseInfo(Encoding encoding, RequestInfo request, HeaderCollection headers) : base(encoding, request, headers)
 {
 }
Exemple #14
0
        /// <summary>Parses a given string as a <see cref="HeaderCollection" />.</summary>
        /// <param name="headers">String to be parsed.</param>
        /// <returns>Instance of the <see cref="HeaderCollection" />.</returns>
        public static HeaderCollection Parse(string headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException("headers");
            }

            if (headers.Length == 0)
            {
                throw new ArgumentOutOfRangeException("headers");
            }

            HeaderCollection result = new HeaderCollection();
            var matches = Header.Matches(headers);
            foreach (Match match in matches)
            {
                result.Add(Http.Header.Parse(match.Value));
            }

            return result;
        }
Exemple #15
0
        /// <summary>Calls the ReST service using specified HTTP verb.</summary>
        /// <param name="verb">The HTTP verb.</param>
        /// <param name="url">Relative URL of the service to call.</param>
        /// <param name="accept">Enumeration of accepted media types.</param>
        /// <param name="contentType">Enumeration of possible content type media types.</param>
        /// <param name="responseType">Type of the response.</param>
        /// <param name="uriArguments">The URI template arguments.</param>
        /// <param name="bodyArguments">The body arguments.</param>
        /// <returns>Result of the call.</returns>
        protected object Call(Verb verb, string url, IEnumerable <string> accept, IEnumerable <string> contentType, Type responseType, IDictionary <string, object> uriArguments, params object[] bodyArguments)
        {
            var callUrl     = BuildUrl(url, uriArguments);
            var validAccept = (!accept.Any() ? _converterProvider.SupportedMediaTypes :
                               _converterProvider.SupportedMediaTypes.Join(accept, outer => outer, inner => inner, (outer, inner) => inner));
            var        accepted = (validAccept.Any() ? validAccept : new[] { "*/*" });
            WebRequest request  = _webRequestProvider.CreateRequest((Uri)callUrl, new Dictionary <string, string>()
            {
                { Header.Accept, String.Join(", ", accepted) }
            });

            if ((!String.IsNullOrEmpty(CredentialCache.DefaultNetworkCredentials.UserName)) && (!String.IsNullOrEmpty(CredentialCache.DefaultNetworkCredentials.Password)))
            {
                var credentials = new CredentialCache();
                credentials.Add(new Uri(callUrl.Authority), _authenticationScheme, new NetworkCredential(CredentialCache.DefaultNetworkCredentials.UserName, CredentialCache.DefaultNetworkCredentials.Password));
                request.Credentials     = credentials;
                request.PreAuthenticate = true;
            }

            request.Method = verb.ToString();
            if ((bodyArguments != null) && (bodyArguments.Length > 0))
            {
                FillRequestBody(verb, callUrl, request, contentType, accepted, bodyArguments);
            }

            var response = (HttpWebResponse)request.GetResponse();

            ParseContentRange(response, uriArguments);
            if (responseType == null)
            {
                return(null);
            }

            RequestInfo fakeRequest = new RequestInfo(verb, callUrl, response.GetResponseStream(), new BasicClaimBasedIdentity(), HeaderCollection.Parse(response.Headers.ToString()));
            var         result      = _resultBinder.BindResults(responseType, fakeRequest);

            return(result.FirstOrDefault(responseType.IsInstanceOfType));
        }
Exemple #16
0
 public ResponseInfo(RequestInfo request, HeaderCollection headers) : this(Encoding.UTF8, request, headers)
 {
 }
        public void it_should_merge_headers()
        {
            var headers1 = new HeaderCollection(new Header("test1"));
            var headers2 = new HeaderCollection(new Header("test2"));

            headers1.Merge(headers2);

            headers1.Should().ContainKey("test2");
        }
 public MultiObjectResponseInfo(Encoding encoding, RequestInfo request, IEnumerable<object> values, IConverterProvider converterProvider, HeaderCollection headers) :
     base(encoding, request, headers)
 {
     Initialize(encoding, request, values, converterProvider);
 }
 public MultiObjectResponseInfo(RequestInfo request, IEnumerable<object> values, IConverterProvider converterProvider, HeaderCollection headers) :
     this(Encoding.UTF8, request, values, converterProvider, headers)
 {
 }
        public void it_should_bind_arguments_for_Upload_method_correctly()
        {
            string fileName = "test.txt";
            byte[] data = new byte[] { 1, 2 };
            _fromQueryStringBinder.Setup(instance => instance.GetArgumentValue(It.IsAny<ArgumentBindingContext>()))
                .Returns<ArgumentBindingContext>(context => (context.Index == 0 ? (object)fileName : (object)data));
            var method = ControllerType.GetMethod("Upload");
            string body = String.Format(
                "--test\r\nContentType: text/plain\r\nContent-Lenght: {0}\r\nContent-Disposition: form-data; name=\"filename\"\r\n\r\n{1}\r\n" +
                "--test\r\nContentType: text/plain\r\nContent-Length: {2}\r\nContent-Disposition: form-data; name=\"data\"\r\n\r\n{3}\r\n" +
                "--test--",
                fileName.Length + 2,
                fileName,
                System.Convert.ToBase64String(data).Length + 2,
                System.Convert.ToBase64String(data));
            var headers = new HeaderCollection();
            headers.ContentType = "multipart/form-data; boundary=\"test\"";
            headers.ContentLength = body.Length;
            var arguments = BindArguments("/api/test/upload", method, Verb.POST);

            arguments.Length.Should().Be(method.GetParameters().Length);
            arguments[0].Should().Be(fileName);
            ((byte[])arguments[1]).Should().BeEquivalentTo(data);
        }
 public void it_should_set_and_get_named_headers_correctly()
 {
     var collection = new HeaderCollection();
     foreach (var namedHeader in collection.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
         .Where(property => (property.CanRead) && (property.CanWrite) && (property.Name != "Item")))
     {
         var value = (namedHeader.PropertyType == typeof(string) ? (object)"test" : 1);
         namedHeader.SetValue(collection, value);
         namedHeader.GetValue(collection).Should().Be(value);
     }
 }
        public void it_should_bind_arguments_for_Modulo_method_correctly()
        {
            _fromQueryStringBinder.Setup(instance => instance.GetArgumentValue(It.IsAny<ArgumentBindingContext>()))
                .Returns<ArgumentBindingContext>(context => (context.Index == 0 ? 1 : 2));
            var method = ControllerType.GetMethod("PostModulo");
            var body =
                "--test\r\nContent-Type: text/plain\r\nContent-Length:3\r\n\r\n1\r\n" +
                "--test\r\nContent-Type: text/plain\r\nContent-Length:3\r\n\r\n2\r\n--test--";
            var headers = new HeaderCollection();
            headers.ContentLength = body.Length;
            ((IDictionary<string, string>)headers)["Content-Type"] = "multipart/mixed; boundary=\"test\"";
            var arguments = BindArguments("/api/test/modulo", method, Verb.POST);

            arguments.Length.Should().Be(method.GetParameters().Length);
            arguments[0].Should().Be(1);
            arguments[1].Should().Be(2);
        }
Exemple #23
0
 public ResponseInfo(RequestInfo request, HeaderCollection headers) : this(Encoding.UTF8, request, headers)
 {
 }
Exemple #24
0
        public RequestInfo(Verb method, HttpUrl url, Stream body, IClaimBasedIdentity identity, HeaderCollection headers)
        {
            if (method == null)
            {
                throw new ArgumentNullException("method");
            }

            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            if (body == null)
            {
                throw new ArgumentNullException("body");
            }

            if (identity == null)
            {
                throw new ArgumentNullException("identity");
            }

            Method    = method;
            Url       = url;
            Body      = new UnclosableStream(_stream = body);
            _identity = identity;
            Headers   = headers ?? new HeaderCollection();
        }
Exemple #25
0
        /// <summary>Merges headers.</summary>
        /// <param name="headers">Headers to be merged.</param>
        public void Merge(HeaderCollection headers)
        {
            if (headers == null)
            {
                return;
            }

            foreach (var header in headers)
            {
                Add(header);
            }
        }
        public void it_should_do_nothing_when_no_headers_is_being_merged()
        {
            var headers = new HeaderCollection();

            headers.Merge(null);

            headers.Should().HaveCount(0);
        }