Describes an HTTP request.
Inheritance: IRequestInfo, IDisposable
 public void Setup()
 {
     (_converterProvider = new Mock<IConverterProvider>(MockBehavior.Strict)).Setup(instance => instance.FindBestOutputConverter<string>(It.IsAny<IResponseInfo>()))
         .Returns<IResponseInfo>(response => _converter.Object);
     _converterProvider.Setup(instance => instance.FindBestOutputConverter<int>(It.IsAny<IResponseInfo>()))
         .Returns<IResponseInfo>(response => _converter.Object);
     (_converter = new Mock<IConverter>(MockBehavior.Strict)).Setup(instance => instance.CanConvertFrom<string>(It.IsAny<IResponseInfo>()))
         .Returns<IResponseInfo>(response => CompatibilityLevel.ExactMatch);
     _converter.Setup(instance => instance.ConvertFrom(StringBody, It.IsAny<IResponseInfo>()))
         .Callback<string, IResponseInfo>((body, response) =>
         {
             response.Headers["Content-Type"] = "text/plain";
             using (var writer = new StreamWriter(response.Body))
             {
                 writer.Write(body);
                 writer.Flush();
             }
         });
     _converter.Setup(instance => instance.ConvertFrom(NumericBody, It.IsAny<IResponseInfo>()))
         .Callback<int, IResponseInfo>((body, response) =>
         {
             response.Headers["Content-Type"] = "text/plain";
             using (var writer = new StreamWriter(response.Body))
             {
                 writer.Write(body);
                 writer.Flush();
             }
         });
     _request = new RequestInfo(Verb.GET, (HttpUrl)UrlParser.Parse("http://temp.org/"), new MemoryStream(), new BasicClaimBasedIdentity());
     _response = new MultiObjectResponseInfo(_request, new object[] { StringBody, NumericBody }, _converterProvider.Object);
 }
        public void it_should_allow_methods_in_CORS_request()
        {
            var controller = new OptionsController(HttpStatusCode.MethodNotAllowed, "GET");
            var request = new RequestInfo(Verb.OPTIONS, (HttpUrl)UrlParser.Parse("/"), new MemoryStream(), new BasicClaimBasedIdentity(), new Header("Origin", "temp.uri"), new Header("Access-Control-Request-Method", "GET"));
            controller.Response = new StringResponseInfo(String.Empty, request);

            controller.Allow();

            controller.Response.Headers["Access-Control-Allow-Methods"].Should().Be("GET");
        }
Exemple #3
0
        public void it_should_bind_response_object()
        {
            var expected = new Person() { Key = 1, FirstName = "test", LastName = "test", Roles = new[] { "test" } };
            var body = new MemoryStream();
            new JsonSerializer().Serialize(new StreamWriter(body), expected);
            body.Seek(0, SeekOrigin.Begin);
            var request = new RequestInfo(Verb.GET, (HttpUrl)UrlParser.Parse("http://temp.uri/"), body, new BasicClaimBasedIdentity(), new Header("Content-Type", "application/json"));
            _converterProvider.Setup(instance => instance.FindBestInputConverter(typeof(Person), request, false)).Returns(_converter.Object);
            _converter.Setup(instance => instance.ConvertTo(typeof(Person), request)).Returns(expected);

            var result = _resultBinder.BindResults<Person>(request);

            result.Should().HaveCount(1);
            result[0].Should().Be(expected);
        }
Exemple #4
0
        public StringResponseInfo(Encoding encoding, string content, RequestInfo request) : base(encoding, request)
        {
            if (content != null)
            {
                _body = new MemoryStream(Encoding.GetBytes(Content = content));
            }
            else
            {
                Content = null;
                _body = new MemoryStream();
            }

            _body.Seek(0, SeekOrigin.Begin);
            Body = new UnclosableStream(_body);
        }
Exemple #5
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 #6
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 #7
0
        public void it_should_bind_response_from_header()
        {
            var expected = Guid.NewGuid();
            var request = new RequestInfo(
                Verb.GET,
                (HttpUrl)UrlParser.Parse("http://temp.uri/"),
                new MemoryStream(),
                new BasicClaimBasedIdentity(),
                new Header("Content-Type", "text/plain"),
                new Header("Location", "http://temp.uri/" + expected));
            _converterProvider.Setup(instance => instance.FindBestInputConverter(typeof(Guid), request, false)).Returns((IConverter)null);

            var result = _resultBinder.BindResults<Guid>(request);

            result.Should().HaveCount(1);
            result[0].Should().Be(expected);
        }
Exemple #8
0
 public ResponseInfo(RequestInfo request, HeaderCollection headers) : this(Encoding.UTF8, request, headers)
 {
 }
Exemple #9
0
 public ResponseInfo(RequestInfo request, params Header[] headers) : this(Encoding.UTF8, request, headers)
 {
 }
Exemple #10
0
 protected ObjectResponseInfo(Encoding encoding, RequestInfo request, HeaderCollection headers) : base(encoding, request, headers)
 {
 }
Exemple #11
0
 protected ObjectResponseInfo(Encoding encoding, RequestInfo request, params Header[] headers) : base(encoding, request, headers)
 {
 }
Exemple #12
0
 public ResponseInfo(RequestInfo request, HeaderCollection headers) : this(Encoding.UTF8, request, headers)
 {
 }
Exemple #13
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);
        }
        private object[] BindArguments(string callUri, MethodInfo method, Verb verb, bool indirectly = false)
        {
            var methodUri = Regex.Replace(callUri, "\\?.+", String.Empty);
            var queryStringParameters = Regex.Matches(callUri, "[?&]([^=]+)=[^&]+").Cast<System.Text.RegularExpressions.Match>();
            var queryStringRegex = (queryStringParameters.Any() ? "[?&](" + String.Join("|", queryStringParameters.Select(item => item.Groups[1].Value)) + ")=[^&]+" : String.Empty);
            var arguments = method.GetParameters()
                .Select(item => new ArgumentInfo(item, FromQueryStringAttribute.For(item), "&test={?test}", "test"));
            var operation = new OperationInfo<Verb>(
                method,
                (HttpUrl)UrlParser.Parse(methodUri),
                callUri,
                new Regex("^" + methodUri + queryStringRegex + "$"),
                verb,
                arguments.ToArray());
            var request = new RequestInfo(Verb.GET, (HttpUrl)UrlParser.Parse("http://temp.uri" + callUri), new MemoryStream(), new BasicClaimBasedIdentity());
            var mapping = new RequestMapping(GetControllerInstance(), operation, (HttpUrl)UrlParser.Parse(methodUri));
            if (indirectly)
            {
                return _binder.BindArguments((IRequestInfo)request, (IRequestMapping)mapping);
            }

            return _binder.BindArguments(request, mapping);
        }
 public void it_should_throw_when_no_request_mapping_is_provided()
 {
     var request = new RequestInfo(Verb.GET, (HttpUrl)UrlParser.Parse("/"), new MemoryStream(), new BasicClaimBasedIdentity());
     _binder.Invoking(instance => instance.BindArguments(request, null)).ShouldThrow<ArgumentNullException>().Which.ParamName.Should().Be("requestMapping");
 }
 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)
 {
 }
        private void Initialize(Encoding encoding, RequestInfo request, IEnumerable<object> values, IConverterProvider converterProvider)
        {
            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            var boundary = Guid.NewGuid().ToString();
            Headers.ContentType = String.Format("multipart/mixed; boundary=\"{0}\"", boundary);
            _body = new MemoryStream();
            Body = new UnclosableStream(_body);
            var valueResponses = new List<ResponseInfo>();
            using (var writer = new StreamWriter(Body))
            {
                foreach (var value in values.Where(value => value != null))
                {
                    writer.Write("--{0}\r\n", boundary);
                    var objectResponse = ObjectResponseInfo<object>.CreateInstance(encoding, request, value.GetType(), value, converterProvider);
                    valueResponses.Add(objectResponse);
                    foreach (var header in objectResponse.Headers)
                    {
                        switch (header.Name)
                        {
                            case "Content-Lenght":
                                break;
                            default:
                                writer.Write("{0}\r\n", header);
                                break;
                        }
                    }

                    writer.Write("Content-Length:{0}\r\n\r\n", objectResponse.Body.Length);
                    writer.Flush();
                    objectResponse.Body.CopyTo(Body);
                    writer.Flush();
                    writer.Write("\r\n");
                    writer.Flush();
                }

                writer.Write("--{0}--", boundary);
                writer.Flush();
            }

            _body.Seek(0, SeekOrigin.Begin);
            ObjectResponses = valueResponses;
        }
Exemple #19
0
 public void Setup()
 {
     _request = RequestInfo.Parse(Verb.GET, Url, Message);
 }
Exemple #20
0
 public StringResponseInfo(string content, RequestInfo request) : this(Encoding.UTF8, content, request)
 {
 }
Exemple #21
0
 public void Teardown()
 {
     _request = null;
 }
Exemple #22
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 #23
0
 public ResponseInfo(RequestInfo request, params Header[] headers) : this(Encoding.UTF8, request, headers)
 {
 }
 public void Teardown()
 {
     _converter = null;
     _converterProvider = null;
     _request = null;
 }
Exemple #25
0
 public StringResponseInfo(string content, RequestInfo request) : this(Encoding.UTF8, content, request)
 {
 }