/// <summary>
 /// Sets the route HTTP request message to test using a builder.
 /// </summary>
 /// <param name="httpRequestMessageBuilder">Builder for HTTP request message.</param>
 /// <returns>Route test builder.</returns>
 public IShouldMapTestBuilder ShouldMap(Action<IHttpRequestMessageBuilder> httpRequestMessageBuilder)
 {
     var httpBuilder = new HttpRequestMessageBuilder();
     httpRequestMessageBuilder(httpBuilder);
     var requestMessage = httpBuilder.GetHttpRequestMessage();
     return this.ShouldMap(requestMessage);
 }
Esempio n. 2
0
        public void Builder_Creates_New_Request()
        {
            var builder = new HttpRequestMessageBuilder();

            builder.HttpRequestMessage.Should().NotBeNull();
        }
        public void ProcessParameter(HttpRequestMessageBuilder requestBuilder, ParameterInfo parameterInfo, object parameterValue)
        {
            Action <object> process = (pv) =>
            {
                HttpContent content = null;
                if (pv is HttpContent)
                {
                    content = pv as HttpContent;
                }
                else
                {
                    var dispositionName    = "\"" + (!string.IsNullOrWhiteSpace(this.Name) ? this.Name : parameterInfo.Name) + "\"";
                    var contentDisposition = new ContentDispositionHeaderValue(
                        requestBuilder.MultiPartAttribute != null ? requestBuilder.MultiPartAttribute.MultiPartType : MultiPartType.FormData
                        );

                    if (pv is Stream)
                    {
                        var s = pv as Stream;
                        content = new StreamContent(s);
                    }
                    else if (pv is IEnumerable <byte> )
                    {
                        var s = new MemoryStream((pv as IEnumerable <byte>).ToArray());
                        content = new StreamContent(s);
                    }
                    else
                    {
                        var val = Convert.ToString(pv);
                        content = new StringContent(val);
                    }

                    if (!string.IsNullOrWhiteSpace(this.ContentType))
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue(this.ContentType);
                    }

                    content.Headers.ContentDisposition      = contentDisposition;
                    content.Headers.ContentDisposition.Name = dispositionName;
                }

                requestBuilder.RawContents.Add(content);
            };

            if (parameterValue != null)
            {
                if (typeof(IEnumerable).IsAssignableFrom(parameterValue.GetType()))
                {
                    foreach (var pv in parameterValue as IEnumerable)
                    {
                        process(pv);
                    }
                }
                else if (parameterValue.GetType().IsArray)
                {
                    foreach (var pv in parameterValue as Array)
                    {
                        process(pv);
                    }
                }
                else
                {
                    process(parameterValue);
                }
            }
            else
            {
                throw new NotSupportedException("parameterValue not allow null");
            }
        }
Esempio n. 4
0
        private ParserState ProcessRequest(HttpRequestMessageBuilder request, ParserState currentState, string content)
        {
            switch (currentState)
            {
                case ParserState.RequestLine:
                    // From RFC2616: "In the interest of robustness, servers SHOULD ignore any empty line(s) received where a Request-Line is expected."
                    if (content.Length == 0)
                    {
                        return currentState;
                    }

                    var requestLine = content.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    // Verbs are case-sensitive
                    switch (requestLine.Length > 0 ? requestLine[0] : null)
                    {
                        case "OPTIONS":
                            request.Method = HttpMethod.Options;
                            break;
                        case "GET":
                            request.Method = HttpMethod.Get;
                            break;
                        case "HEAD":
                            request.Method = HttpMethod.Head;
                            break;
                        case "POST":
                            request.Method = HttpMethod.Post;
                            break;
                        case "PUT":
                            request.Method = HttpMethod.Put;
                            break;
                        case "DELETE":
                            request.Method = HttpMethod.Delete;
                            break;
                        case "TRACE":
                            request.Method = HttpMethod.Trace;
                            break;
                        default: break;
                    }

                    request.RequestUri = ResolveTargetUri(requestLine.Length > 1 ? requestLine[1] : "/");

                    var protocolVersion = Regex.Match(requestLine.Length > 2 ? requestLine[2] : null, "HTTP/(?<version>.*)").Groups["version"].Value;
                    Version version;
                    if (Version.TryParse(protocolVersion, out version))
                    {
                        request.Version = version;
                    }

                    return ParserState.RequestHeaders;

                case ParserState.RequestHeaders:
                    // empty line signals end of request header
                    if (content.Length > CrLf.Length)
                    {
                        // Header names are case-insensitive
                        var header = content.Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
                        var headerName = header.Length > 0 ? header[0].Trim() : null;
                        var headerValue = header.Length > 1 ? header[1].Trim() : null;
                        if (headerName != null && headerValue != null)
                        {
                            switch (headerName.ToUpperInvariant())
                            {
                                case "RANGE":
                                    // fixes issue in HttpClient for WP where a Range header with no upper range 
                                    // results in an InvalidOperationException - "Nullable object must have a value"
                                    if (headerValue.EndsWith("-"))
                                    {
                                        headerValue += long.MaxValue.ToString();
                                    }

                                    request.Headers.Add(headerName, headerValue);
                                    break;

                                case "REFERER":
                                    headerValue = ResolveTargetUri(headerValue).AbsoluteUri;
                                    request.Headers.Add(headerName, headerValue);
                                    break;

                                case "HOST":
                                    break;

                                case "CONNECTION":
                                    break;

                                case "ALLOW":
                                case "CONTENT-ENCODING":
                                case "CONTENT-LANGUAGE":
                                    request.ContentHeaders[headerName] = headerValue;
                                    break;

                                case "CONTENT-DISPOSITION":
                                    ContentDispositionHeaderValue contentDisposition;
                                    if (ContentDispositionHeaderValue.TryParse(headerValue, out contentDisposition))
                                    {
                                        request.ContentHeaders[headerName] = contentDisposition;
                                    }

                                    break;

                                case "CONTENT-LENGTH":
                                    long contentLength;
                                    if (long.TryParse(headerValue, out contentLength))
                                    {
                                        request.ContentHeaders[headerName] = contentLength;
                                    }

                                    break;

                                case "CONTENT-LOCATION":
                                    var contentLocation = ResolveTargetUri(headerValue).AbsoluteUri;
                                    request.ContentHeaders[headerName] = contentLocation;
                                    break;

                                case "CONTENT-MD5":
                                    // currently not supported
                                    break;

                                case "CONTENT-RANGE":
                                    ContentRangeHeaderValue contentRange;
                                    if (ContentRangeHeaderValue.TryParse(headerValue, out contentRange))
                                    {
                                        request.ContentHeaders[headerName] = contentRange;
                                    }

                                    break;

                                case "CONTENT-TYPE":
                                    MediaTypeHeaderValue contentType;
                                    if (MediaTypeHeaderValue.TryParse(headerValue, out contentType))
                                    {
                                        request.ContentHeaders[headerName] = contentType;
                                    }

                                    break;

                                case "CONTENT-EXPIRES":
                                case "CONTENT-LASTMODIFIED":
                                    DateTimeOffset expires;
                                    if (DateTimeOffset.TryParse(headerValue, out expires))
                                    {
                                        request.ContentHeaders[headerName] = expires;
                                    }

                                    break;

                                case "USER-AGENT":
                                    request.Headers.TryAddWithoutValidation("User-Agent", headerValue.Replace(")", "; WAT)"));
                                    break;

                                case "COOKIE":
                                    // filter out cookies for other domains
                                    var filteredCookies = cookieManager.FilterCookiesForCurrentRequest(request.RequestUri, headerValue);
                                    if (!string.IsNullOrWhiteSpace(filteredCookies))
                                    {
                                        request.Headers.Add(headerName, filteredCookies);
                                    }

                                    break;

                                default:
                                    request.Headers.Add(headerName, headerValue);
                                    break;
                            }
                        }
                    }
                    else
                    {
                        currentState = ParserState.RequestBody;
                    }

                    break;

                case ParserState.RequestBody:
                    request.Content = new StringContent(content);
                    currentState = ParserState.Complete;
                    break;
            }

            return currentState;
        }
Esempio n. 5
0
        private async Task<HttpRequestMessage> ReadRequestAsync(StreamSocket socket, Guid requestId)
        {
            var currentState = ParserState.RequestLine;
            var request = new HttpRequestMessageBuilder();

            var lineBuffer = new StringBuilder();
            byte[] requestBuffer = null;
            int bufferPosition = 0;
            using (var reader = new DataReader(socket.InputStream))
            {
                reader.InputStreamOptions = InputStreamOptions.Partial;

                var encoding = Encoding.GetEncoding("ISO-8859-1");
                var decoder = encoding.GetDecoder();
                while (currentState < ParserState.RequestBody)
                {
                    var bytesRead = await reader.LoadAsync(BufferSize);

                    if (bytesRead == 0)
                    {
                        Trace.Information(requestId, "Disconnected from: {0}", socket.Information.RemoteHostName.DisplayName);
                        return null;
                    }

                    requestBuffer = new byte[bytesRead];
                    reader.ReadBytes(requestBuffer);
                    bufferPosition = 0;
                    bool inputConsumed = false;
                    var charBuffer = new char[1];
                    int bytesUsed, charsUsed;

                    while (!inputConsumed)
                    {
                        decoder.Convert(
                            requestBuffer,
                            bufferPosition,
                            requestBuffer.Length - bufferPosition,
                            charBuffer,
                            0,
                            1,
                            requestBuffer.Length == 0,
                            out bytesUsed,
                            out charsUsed,
                            out inputConsumed);

                        bufferPosition += bytesUsed;
                        if (charsUsed > 0)
                        {
                            lineBuffer.Append(charBuffer[0]);
                            if (lineBuffer.Length > 1 && lineBuffer[lineBuffer.Length - 2] == '\r' && lineBuffer[lineBuffer.Length - 1] == '\n')
                            {
                                if (lineBuffer.Length == 2 && currentState == ParserState.RequestHeaders)
                                {
                                    currentState = ParserState.RequestBody;
                                    break;
                                }

                                Trace.Verbose(requestId, "Processing line: {0}", lineBuffer.ToString(0, lineBuffer.Length - 2));
                                currentState = ProcessRequest(request, currentState, lineBuffer.ToString());
                                lineBuffer.Clear();
                            }
                        }
                    }
                }

                while (currentState != ParserState.Complete)
                {
                    long contentLength = 0;
                    object headerValue;
                    if (request.ContentHeaders.TryGetValue("CONTENT-LENGTH", out headerValue))
                    {
                        contentLength = (long)headerValue;
                    }

                    if (contentLength > 0)
                    {
                        var requestBody = new byte[contentLength];
                        var availableBytes = requestBuffer.Length - bufferPosition;
                        if (availableBytes > 0)
                        {
                            Array.Copy(requestBuffer, bufferPosition, requestBody, 0, availableBytes);
                        }

                        while (availableBytes < contentLength)
                        {
                            var bytesRead = await reader.LoadAsync(BufferSize);
                            if (bytesRead == 0)
                            {
                                Trace.Information(requestId, "Disconnected from: {0}", socket.Information.RemoteHostName.DisplayName);
                                return null;
                            }

                            requestBuffer = new byte[bytesRead];
                            reader.ReadBytes(requestBuffer);
                            Array.Copy(requestBuffer, 0, requestBody, availableBytes, (int)bytesRead);
                            availableBytes += (int)bytesRead;
                        }

                        request.Content = new ByteArrayContent(requestBody);
                        foreach (var header in request.ContentHeaders)
                        {
                            switch (header.Key.ToUpperInvariant())
                            {
                                case "ALLOW":
                                case "CONTENT-ENCODING":
                                case "CONTENT-LANGUAGE":
                                    request.Content.Headers.Add(header.Key, (string)header.Value);
                                    break;

                                case "CONTENT-DISPOSITION":
                                    request.Content.Headers.ContentDisposition = (ContentDispositionHeaderValue)header.Value;
                                    break;

                                case "CONTENT-LENGTH":
                                    request.Content.Headers.ContentLength = contentLength;
                                    break;

                                case "CONTENT-LOCATION":
                                    request.Content.Headers.ContentLocation = (Uri)header.Value;
                                    break;

                                case "CONTENT-MD5":
                                    // currently not supported
                                    break;

                                case "CONTENT-RANGE":
                                    request.Content.Headers.ContentRange = (ContentRangeHeaderValue)header.Value;
                                    break;

                                case "CONTENT-TYPE":
                                    request.Content.Headers.ContentType = (MediaTypeHeaderValue)header.Value;
                                    break;

                                case "CONTENT-EXPIRES":
                                    request.Content.Headers.Expires = (DateTimeOffset)header.Value;
                                    break;

                                case "CONTENT-LASTMODIFIED":
                                    request.Content.Headers.LastModified = (DateTimeOffset)header.Value;
                                    break;
                            }
                        }

                        Trace.Verbose(
                            requestId,
                            "Processing body: {0}, Content-Type: {1}, Content-Length: {2}",
                            lineBuffer.ToString(),
                            request.Content.Headers.ContentType,
                            request.Content.Headers.ContentLength);
                    }

                    currentState = ParserState.Complete;
                }
            }

            return request;
        }
Esempio n. 6
0
 public Task SendAsync(HttpRequestMessageBuilder builder, CancellationToken cancellationToken)
 {
     return(SendAsync(builder, default(HttpCompletionOption), cancellationToken));
 }
Esempio n. 7
0
 public Task <TResponseType> SendAsync <TResponseType>(HttpRequestMessageBuilder builder, CancellationToken cancellationToken)
 {
     return(SendAsync <TResponseType>(builder, default(HttpCompletionOption), cancellationToken));
 }
Esempio n. 8
0
        internal void ProcessParameter(HttpRequestMessageBuilder requestBuilder, object parameterValue)
        {
            var pFormatAttr = requestBuilder.DefaultStringFormatter;

            requestBuilder.Headers.AddRange(Utility.ExtractUrlParameter(this.Name, parameterValue, pFormatAttr, 1));
        }
Esempio n. 9
0
        public async Task <string> Search(string q, string lang = default, int?limit = default, float?lat = default, float?lon = default, int?location_bias_scale = default, string bbox = default, string[] osm_tags = default, CancellationToken cancellationToken = default)
        {
            var url = $"{applicationOptions.Photon?.ApiUrl}";

            var httpRequestMessageBuilder = new HttpRequestMessageBuilder(url, HttpMethod.Get);

            httpRequestMessageBuilder.AddQueryString("q", q);

            if (!string.IsNullOrWhiteSpace(lang))
            {
                httpRequestMessageBuilder.AddQueryString("lang", lang);
            }

            if (limit.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("limit", limit.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (lat.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("lat", lat.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (lon.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("lon", lon.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (location_bias_scale.HasValue)
            {
                httpRequestMessageBuilder.AddQueryString("location_bias_scale", location_bias_scale.Value.ToString(CultureInfo.InvariantCulture));
            }

            if (!string.IsNullOrWhiteSpace(bbox))
            {
                httpRequestMessageBuilder.AddQueryString("bbox", bbox);
            }

            if (osm_tags != null)
            {
                foreach (var osm_tag in osm_tags)
                {
                    httpRequestMessageBuilder.AddQueryString("osm_tag", osm_tag);
                }
            }

            var httpRequestMessage = httpRequestMessageBuilder.Build();

            var httpResponse = await httpClient
                               .SendAsync(httpRequestMessage)
                               .ConfigureAwait(false);

            if (!httpResponse.IsSuccessStatusCode)
            {
                var statusCode = httpResponse.StatusCode;
                var reason     = httpResponse.ReasonPhrase;

                throw new Exception($"API Request failed with Status Code {statusCode} and Reason {reason}. For additional information, see the HttpResponseMessage in this Exception.");
            }

            return(await httpResponse.Content
                   .ReadAsStringAsync()
                   .ConfigureAwait(false));
        }
Esempio n. 10
0
        private ParserState ProcessRequest(HttpRequestMessageBuilder request, ParserState currentState, string content)
        {
            switch (currentState)
            {
            case ParserState.RequestLine:
                // From RFC2616: "In the interest of robustness, servers SHOULD ignore any empty line(s) received where a Request-Line is expected."
                if (content.Length == 0)
                {
                    return(currentState);
                }

                var requestLine = content.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                // Verbs are case-sensitive
                switch (requestLine.Length > 0 ? requestLine[0] : null)
                {
                case "OPTIONS":
                    request.Method = HttpMethod.Options;
                    break;

                case "GET":
                    request.Method = HttpMethod.Get;
                    break;

                case "HEAD":
                    request.Method = HttpMethod.Head;
                    break;

                case "POST":
                    request.Method = HttpMethod.Post;
                    break;

                case "PUT":
                    request.Method = HttpMethod.Put;
                    break;

                case "DELETE":
                    request.Method = HttpMethod.Delete;
                    break;

                case "TRACE":
                    request.Method = HttpMethod.Trace;
                    break;

                default: break;
                }

                request.RequestUri = ResolveTargetUri(requestLine.Length > 1 ? requestLine[1] : "/");

                var     protocolVersion = Regex.Match(requestLine.Length > 2 ? requestLine[2] : null, "HTTP/(?<version>.*)").Groups["version"].Value;
                Version version;
                if (Version.TryParse(protocolVersion, out version))
                {
                    request.Version = version;
                }

                return(ParserState.RequestHeaders);

            case ParserState.RequestHeaders:
                // empty line signals end of request header
                if (content.Length > CrLf.Length)
                {
                    // Header names are case-insensitive
                    var header      = content.Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
                    var headerName  = header.Length > 0 ? header[0].Trim() : null;
                    var headerValue = header.Length > 1 ? header[1].Trim() : null;
                    if (headerName != null && headerValue != null)
                    {
                        switch (headerName.ToUpperInvariant())
                        {
                        case "RANGE":
                            // fixes issue in HttpClient for WP where a Range header with no upper range
                            // results in an InvalidOperationException - "Nullable object must have a value"
                            if (headerValue.EndsWith("-"))
                            {
                                headerValue += long.MaxValue.ToString();
                            }

                            request.Headers.Add(headerName, headerValue);
                            break;

                        case "REFERER":
                            headerValue = ResolveTargetUri(headerValue).AbsoluteUri;
                            request.Headers.Add(headerName, headerValue);
                            break;

                        case "HOST":
                            break;

                        case "CONNECTION":
                            break;

                        case "ALLOW":
                        case "CONTENT-ENCODING":
                        case "CONTENT-LANGUAGE":
                            request.ContentHeaders[headerName] = headerValue;
                            break;

                        case "CONTENT-DISPOSITION":
                            ContentDispositionHeaderValue contentDisposition;
                            if (ContentDispositionHeaderValue.TryParse(headerValue, out contentDisposition))
                            {
                                request.ContentHeaders[headerName] = contentDisposition;
                            }

                            break;

                        case "CONTENT-LENGTH":
                            long contentLength;
                            if (long.TryParse(headerValue, out contentLength))
                            {
                                request.ContentHeaders[headerName] = contentLength;
                            }

                            break;

                        case "CONTENT-LOCATION":
                            var contentLocation = ResolveTargetUri(headerValue).AbsoluteUri;
                            request.ContentHeaders[headerName] = contentLocation;
                            break;

                        case "CONTENT-MD5":
                            // currently not supported
                            break;

                        case "CONTENT-RANGE":
                            ContentRangeHeaderValue contentRange;
                            if (ContentRangeHeaderValue.TryParse(headerValue, out contentRange))
                            {
                                request.ContentHeaders[headerName] = contentRange;
                            }

                            break;

                        case "CONTENT-TYPE":
                            MediaTypeHeaderValue contentType;
                            if (MediaTypeHeaderValue.TryParse(headerValue, out contentType))
                            {
                                request.ContentHeaders[headerName] = contentType;
                            }

                            break;

                        case "CONTENT-EXPIRES":
                        case "CONTENT-LASTMODIFIED":
                            DateTimeOffset expires;
                            if (DateTimeOffset.TryParse(headerValue, out expires))
                            {
                                request.ContentHeaders[headerName] = expires;
                            }

                            break;

                        case "USER-AGENT":
                            request.Headers.TryAddWithoutValidation("User-Agent", headerValue.Replace(")", "; WAT)"));
                            break;

                        case "COOKIE":
                            // filter out cookies for other domains
                            var filteredCookies = this.cookieManager.FilterCookiesForCurrentRequest(request.RequestUri, headerValue);
                            if (!string.IsNullOrWhiteSpace(filteredCookies))
                            {
                                request.Headers.Add(headerName, filteredCookies);
                            }

                            break;

                        default:
                            request.Headers.Add(headerName, headerValue);
                            break;
                        }
                    }
                }
                else
                {
                    currentState = ParserState.RequestBody;
                }

                break;

            case ParserState.RequestBody:
                request.Content = new StringContent(content);
                currentState    = ParserState.Complete;
                break;
            }

            return(currentState);
        }
Esempio n. 11
0
        private async Task <HttpRequestMessage> ReadRequestAsync(StreamSocket socket, Guid requestId)
        {
            var currentState = ParserState.RequestLine;
            var request      = new HttpRequestMessageBuilder();

            var lineBuffer = new StringBuilder();

            byte[] requestBuffer  = null;
            int    bufferPosition = 0;

            using (var reader = new DataReader(socket.InputStream))
            {
                reader.InputStreamOptions = InputStreamOptions.Partial;

                var encoding = Encoding.GetEncoding("ISO-8859-1");
                var decoder  = encoding.GetDecoder();
                while (currentState < ParserState.RequestBody)
                {
                    var bytesRead = await reader.LoadAsync(BufferSize);

                    if (bytesRead == 0)
                    {
                        Trace.Information(requestId, "Disconnected from: {0}", socket.Information.RemoteHostName.DisplayName);
                        return(null);
                    }

                    requestBuffer = new byte[bytesRead];
                    reader.ReadBytes(requestBuffer);
                    bufferPosition = 0;
                    bool inputConsumed = false;
                    var  charBuffer = new char[1];
                    int  bytesUsed, charsUsed;

                    while (!inputConsumed)
                    {
                        decoder.Convert(
                            requestBuffer,
                            bufferPosition,
                            requestBuffer.Length - bufferPosition,
                            charBuffer,
                            0,
                            1,
                            requestBuffer.Length == 0,
                            out bytesUsed,
                            out charsUsed,
                            out inputConsumed);

                        bufferPosition += bytesUsed;
                        if (charsUsed > 0)
                        {
                            lineBuffer.Append(charBuffer[0]);
                            if (lineBuffer.Length > 1 && lineBuffer[lineBuffer.Length - 2] == '\r' && lineBuffer[lineBuffer.Length - 1] == '\n')
                            {
                                if (lineBuffer.Length == 2 && currentState == ParserState.RequestHeaders)
                                {
                                    currentState = ParserState.RequestBody;
                                    break;
                                }

                                Trace.Verbose(requestId, "Processing line: {0}", lineBuffer.ToString(0, lineBuffer.Length - 2));
                                currentState = this.ProcessRequest(request, currentState, lineBuffer.ToString());
                                lineBuffer.Clear();
                            }
                        }
                    }
                }

                while (currentState != ParserState.Complete)
                {
                    long   contentLength = 0;
                    object headerValue;
                    if (request.ContentHeaders.TryGetValue("CONTENT-LENGTH", out headerValue))
                    {
                        contentLength = (long)headerValue;
                    }

                    if (contentLength > 0)
                    {
                        var requestBody    = new byte[contentLength];
                        var availableBytes = requestBuffer.Length - bufferPosition;
                        if (availableBytes > 0)
                        {
                            Array.Copy(requestBuffer, bufferPosition, requestBody, 0, availableBytes);
                        }

                        while (availableBytes < contentLength)
                        {
                            var bytesRead = await reader.LoadAsync(BufferSize);

                            if (bytesRead == 0)
                            {
                                Trace.Information(requestId, "Disconnected from: {0}", socket.Information.RemoteHostName.DisplayName);
                                return(null);
                            }

                            requestBuffer = new byte[bytesRead];
                            reader.ReadBytes(requestBuffer);
                            Array.Copy(requestBuffer, 0, requestBody, availableBytes, (int)bytesRead);
                            availableBytes += (int)bytesRead;
                        }

                        request.Content = new ByteArrayContent(requestBody);
                        foreach (var header in request.ContentHeaders)
                        {
                            switch (header.Key.ToUpperInvariant())
                            {
                            case "ALLOW":
                            case "CONTENT-ENCODING":
                            case "CONTENT-LANGUAGE":
                                request.Content.Headers.Add(header.Key, (string)header.Value);
                                break;

                            case "CONTENT-DISPOSITION":
                                request.Content.Headers.ContentDisposition = (ContentDispositionHeaderValue)header.Value;
                                break;

                            case "CONTENT-LENGTH":
                                request.Content.Headers.ContentLength = contentLength;
                                break;

                            case "CONTENT-LOCATION":
                                request.Content.Headers.ContentLocation = (Uri)header.Value;
                                break;

                            case "CONTENT-MD5":
                                // currently not supported
                                break;

                            case "CONTENT-RANGE":
                                request.Content.Headers.ContentRange = (ContentRangeHeaderValue)header.Value;
                                break;

                            case "CONTENT-TYPE":
                                request.Content.Headers.ContentType = (MediaTypeHeaderValue)header.Value;
                                break;

                            case "CONTENT-EXPIRES":
                                request.Content.Headers.Expires = (DateTimeOffset)header.Value;
                                break;

                            case "CONTENT-LASTMODIFIED":
                                request.Content.Headers.LastModified = (DateTimeOffset)header.Value;
                                break;
                            }
                        }

                        Trace.Verbose(
                            requestId,
                            "Processing body: {0}, Content-Type: {1}, Content-Length: {2}",
                            lineBuffer.ToString(),
                            request.Content.Headers.ContentType,
                            request.Content.Headers.ContentLength);
                    }

                    currentState = ParserState.Complete;
                }
            }

            return(request);
        }
Esempio n. 12
0
        private bool hasPayloadHeader(HttpRequestMessageBuilder request, string headerName)
        {
            Tuple <string, string> match = GetHeaderKV(request, headerName);

            return(match != null);
        }
Esempio n. 13
0
    /// <summary>
    ///     Constructs an HttpRequestMessage builder. For AWS, this function
    ///     has the side-effect of overriding the baseUrl in the HttpClient
    ///     with region specific host path or virtual style path.
    /// </summary>
    /// <param name="method">HTTP method</param>
    /// <param name="bucketName">Bucket Name</param>
    /// <param name="objectName">Object Name</param>
    /// <param name="headerMap">headerMap</param>
    /// <param name="contentType">Content Type</param>
    /// <param name="body">request body</param>
    /// <param name="resourcePath">query string</param>
    /// <returns>A HttpRequestMessage builder</returns>
    /// <exception cref="BucketNotFoundException">When bucketName is invalid</exception>
    internal async Task <HttpRequestMessageBuilder> CreateRequest(
        HttpMethod method,
        string bucketName = null,
        string objectName = null,
        Dictionary <string, string> headerMap = null,
        string contentType  = "application/octet-stream",
        byte[] body         = null,
        string resourcePath = null)
    {
        var region = string.Empty;

        if (bucketName != null)
        {
            utils.ValidateBucketName(bucketName);
            // Fetch correct region for bucket if this is not a bucket creation
            if (!string.IsNullOrEmpty(objectName) && method != HttpMethod.Put)
            {
                region = await GetRegion(bucketName).ConfigureAwait(false);
            }
        }

        if (objectName != null)
        {
            utils.ValidateObjectName(objectName);
        }

        if (Provider != null)
        {
            var isAWSEnvProvider = Provider is AWSEnvironmentProvider ||
                                   (Provider is ChainedProvider ch &&
                                    ch.CurrentProvider is AWSEnvironmentProvider);

            var isIAMAWSProvider = Provider is IAMAWSProvider ||
                                   (Provider is ChainedProvider chained &&
                                    chained.CurrentProvider is AWSEnvironmentProvider);

            AccessCredentials creds = null;

            if (isAWSEnvProvider)
            {
                var aWSEnvProvider = (AWSEnvironmentProvider)Provider;
                creds = await aWSEnvProvider.GetCredentialsAsync();
            }
            else if (isIAMAWSProvider)
            {
                var iamAWSProvider = (IAMAWSProvider)Provider;
                creds = iamAWSProvider.Credentials;
            }
            else
            {
                creds = await Provider.GetCredentialsAsync();
            }

            if (creds != null)
            {
                AccessKey = creds.AccessKey;
                SecretKey = creds.SecretKey;
            }
        }

        // This section reconstructs the url with scheme followed by location specific endpoint (s3.region.amazonaws.com)
        // or Virtual Host styled endpoint (bucketname.s3.region.amazonaws.com) for Amazon requests.
        var resource     = string.Empty;
        var usePathStyle = false;

        if (bucketName != null)
        {
            if (s3utils.IsAmazonEndPoint(BaseUrl))
            {
                if (method == HttpMethod.Put && objectName == null && resourcePath == null)
                {
                    // use path style for make bucket to workaround "AuthorizationHeaderMalformed" error from s3.amazonaws.com
                    usePathStyle = true;
                }
                else if (resourcePath != null && resourcePath.Contains("location"))
                {
                    // use path style for location query
                    usePathStyle = true;
                }
                else if (bucketName != null && bucketName.Contains(".") && Secure)
                {
                    // use path style where '.' in bucketName causes SSL certificate validation error
                    usePathStyle = true;
                }

                if (usePathStyle)
                {
                    resource += utils.UrlEncode(bucketName) + "/";
                }
            }
        }

        // Set Target URL
        var requestUrl = RequestUtil.MakeTargetURL(BaseUrl, Secure, bucketName, region, usePathStyle);

        if (objectName != null)
        {
            resource += utils.EncodePath(objectName);
        }

        // Append query string passed in
        if (resourcePath != null)
        {
            resource += resourcePath;
        }


        HttpRequestMessageBuilder messageBuilder;

        if (!string.IsNullOrEmpty(resource))
        {
            messageBuilder = new HttpRequestMessageBuilder(method, requestUrl, resource);
        }
        else
        {
            messageBuilder = new HttpRequestMessageBuilder(method, requestUrl);
        }
        if (body != null)
        {
            messageBuilder.SetBody(body);
            messageBuilder.AddOrUpdateHeaderParameter("Content-Type", contentType);
        }

        if (headerMap != null)
        {
            if (headerMap.ContainsKey(messageBuilder.ContentTypeKey) &&
                !string.IsNullOrEmpty(headerMap[messageBuilder.ContentTypeKey]))
            {
                headerMap[messageBuilder.ContentTypeKey] = contentType;
            }
            foreach (var entry in headerMap)
            {
                messageBuilder.AddOrUpdateHeaderParameter(entry.Key, entry.Value);
            }
        }

        return(messageBuilder);
    }
Esempio n. 14
0
        public void ProcessParameter(HttpRequestMessageBuilder requestBuilder, ParameterInfo parameterInfo, object parameterValue)
        {
            var pFormatAttr = parameterInfo.GetCustomAttribute <StringFormatAttribute>() ?? requestBuilder.DefaultStringFormatter;

            requestBuilder.Headers.AddRange(Utility.ExtractUrlParameter(this.Name ?? parameterInfo.Name, parameterValue, pFormatAttr, 1));
        }
Esempio n. 15
0
 /// <summary>
 /// Adds HTTP request message to the tested server.
 /// </summary>
 /// <param name="httpRequestMessageBuilder">Builder for HTTP request message.</param>
 /// <returns>Server test builder to test the returned HTTP response.</returns>
 public IServerTestBuilder WithHttpRequestMessage(Action<IHttpRequestMessageBuilder> httpRequestMessageBuilder)
 {
     var httpBuilder = new HttpRequestMessageBuilder();
     httpRequestMessageBuilder(httpBuilder);
     return this.WithHttpRequestMessage(httpBuilder.GetHttpRequestMessage());
 }
 internal override HttpRequestMessageBuilder BuildRequest(HttpRequestMessageBuilder requestMessageBuilder)
 {
     requestMessageBuilder.AddQueryParameter("encryption", "");
     return(requestMessageBuilder);
 }
Esempio n. 17
0
        public void ProcessParameter(HttpRequestMessageBuilder requestBuilder, ParameterInfo parameterInfo, object parameterValue)
        {
            var dispositionName    = "\"" + (!string.IsNullOrWhiteSpace(this.Name) ? this.Name : parameterInfo.Name) + "\"";
            var contentDisposition = new ContentDispositionHeaderValue(
                requestBuilder.MultiPartAttribute != null ? requestBuilder.MultiPartAttribute.MultiPartType : MultiPartType.FormData
                );


            Action <object> process = (pv) =>
            {
                if (pv is string)
                {
                    var f       = new FileInfo(pv.ToString());
                    var content = new StreamContent(f.OpenRead());
                    content.Headers.ContentDisposition          = contentDisposition;
                    content.Headers.ContentDisposition.FileName = f.Name;
                    content.Headers.ContentDisposition.Name     = dispositionName;
                    content.Headers.ContentType = new MediaTypeHeaderValue(!string.IsNullOrWhiteSpace(this.ContentType) ? this.ContentType : MimeUtility.GetMimeMapping(f.Name));

                    requestBuilder.RawContents.Add(content);
                }
                else if (pv is FileInfo)
                {
                    var f       = pv as FileInfo;
                    var content = new StreamContent(f.OpenRead());
                    content.Headers.ContentDisposition          = contentDisposition;
                    content.Headers.ContentDisposition.FileName = f.Name;
                    content.Headers.ContentDisposition.Name     = dispositionName;
                    content.Headers.ContentType = new MediaTypeHeaderValue(!string.IsNullOrWhiteSpace(this.ContentType) ? this.ContentType : MimeUtility.GetMimeMapping(f.Name));

                    requestBuilder.RawContents.Add(content);
                }
                else if (pv is FileStream)
                {
                    var s       = pv as FileStream;
                    var content = new StreamContent(s);
                    content.Headers.ContentDisposition          = contentDisposition;
                    content.Headers.ContentDisposition.FileName = s.Name;
                    content.Headers.ContentDisposition.Name     = dispositionName;
                    content.Headers.ContentType = new MediaTypeHeaderValue(!string.IsNullOrWhiteSpace(this.ContentType) ? this.ContentType : MimeUtility.GetMimeMapping(s.Name));
                    requestBuilder.RawContents.Add(content);
                }
                else
                {
                    throw new NotSupportedException("parameterValue must be String/FileInfo/FileStream");
                }
            };

            if (parameterValue != null)
            {
                if (typeof(IEnumerable).IsAssignableFrom(parameterValue.GetType()))
                {
                    foreach (var pv in parameterValue as IEnumerable)
                    {
                        process(pv);
                    }
                }
                else if (parameterValue.GetType().IsArray)
                {
                    foreach (var pv in parameterValue as Array)
                    {
                        process(pv);
                    }
                }
                else
                {
                    process(parameterValue);
                }
            }
            else
            {
                throw new NotSupportedException("parameterValue not allow null");
            }
        }