Esempio n. 1
0
        private async Task <T> GetRequestBodyAsync <T>(HttpRequest request)
        {
            T objRequestBody = default(T);

            // IMPORTANT: Ensure the requestBody can be read multiple times.
            HttpRequestRewindExtensions.EnableBuffering(request);

            // IMPORTANT: Leave the body open so the next middleware can read it.
            using (
                StreamReader reader = new StreamReader(
                    request.Body,
                    Encoding.UTF8,
                    detectEncodingFromByteOrderMarks: false,
                    leaveOpen: true
                    )
                )
            {
                string strRequestBody = await reader.ReadToEndAsync();

                objRequestBody = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(strRequestBody);

                // IMPORTANT: Reset the request body stream position so the next middleware can read it
                request.Body.Position = 0;
            }

            return(objRequestBody);
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        protected string ReadBody()
        {
            var body = string.Empty;

            try
            {
                var request = _context
                              .HttpContext
                              .Request;

                // IMPORTANT: Ensure the requestBody can be read multiple times.
                HttpRequestRewindExtensions.EnableBuffering(request);

                // Leave the body open so the next middleware can read it.
                using var reader = new StreamReader(
                          request.Body,
                          encoding: Encoding.UTF8,
                          detectEncodingFromByteOrderMarks: false,
                          bufferSize: -1,
                          leaveOpen: true);

                body = reader.ReadToEnd();
                // Do some processing with body…

                // Reset the request body stream position so the next middleware can read it
                request.Body.Position = 0;
            }
            catch { }


            return(body);
        }
        private async Task <string> FormatRequest(HttpRequest request)
        {
            Stream body = null;

            body = request.Body;
            HttpRequestRewindExtensions.EnableBuffering(request);

            //This line allows us to set the reader for the request back at the beginning of its stream.
            //request.EnableRewind();
            //We now need to read the request stream.  First, we create a new byte[] with the same length as the request stream...
            var buffer = new byte[Convert.ToInt32(request.ContentLength)];

            request.Body.Seek(0, SeekOrigin.Begin);

            //...Then we copy the entire request stream into the new buffer.
            await request.Body.ReadAsync(buffer, 0, buffer.Length);

            //We convert the byte[] into a string using UTF8 encoding...
            var bodyAsText = Encoding.UTF8.GetString(buffer);

            //..and finally, assign the read body back to the request body, which is allowed because of EnableRewind()
            request.Body = body;

            return($"{request.Scheme} {request.Host}{request.Path} {request.QueryString} {bodyAsText}");
        }
        private async Task <string> ReadRequestBody(HttpRequest request)
        {
            HttpRequestRewindExtensions.EnableBuffering(request);
            var buffer = new byte[Convert.ToInt32(request.ContentLength)];
            await request.Body.ReadAsync(buffer, 0, buffer.Length);

            var bodyAsText = Encoding.UTF8.GetString(buffer);

            request.Body.Seek(0, SeekOrigin.Begin);

            return(bodyAsText);
        }
Esempio n. 5
0
        private async Task <TRequestBody> ReadBody(HttpRequest request)
        {
            HttpRequestRewindExtensions.EnableBuffering(request);

            using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8, leaveOpen: true))
            {
                var content = await reader.ReadToEndAsync();

                request.Body.Position = 0;
                return(JsonConvert.DeserializeObject <TRequestBody>(content));
            }
        }
Esempio n. 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            // Push the user name into the log context so that it is included in all log entries
            LogContext.PushProperty("UserName", httpContext.User.Identity.Name);

            // Getting the request body is a little tricky because it's a stream
            // So, we need to read the stream and then rewind it back to the beginning
            string requestBody = "";

            HttpRequestRewindExtensions.EnableBuffering(httpContext.Request);
            Stream body = httpContext.Request.Body;

            byte[] buffer = new byte[Convert.ToInt32(httpContext.Request.ContentLength)];
            await httpContext.Request.Body.ReadAsync(buffer, 0, buffer.Length);

            requestBody = Encoding.UTF8.GetString(buffer);
            body.Seek(0, SeekOrigin.Begin);
            httpContext.Request.Body = body;

            Log.ForContext("RequestHeaders", httpContext.Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()), destructureObjects: true)
            .ForContext("RequestBody", requestBody)
            .Debug("Request information {RequestMethod} {RequestPath} information", httpContext.Request.Method, httpContext.Request.Path);

            Log.Debug(string.Format("Request Body: {0} ", requestBody));
            // The reponse body is also a stream so we need to:
            // - hold a reference to the original response body stream
            // - re-point the response body to a new memory stream
            // - read the response body after the request is handled into our memory stream
            // - copy the response in the memory stream out to the original response stream
            using (var responseBodyMemoryStream = new MemoryStream())
            {
                var originalResponseBodyReference = httpContext.Response.Body;
                httpContext.Response.Body = responseBodyMemoryStream;

                await _next(httpContext);

                httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
                var responseBody = await new StreamReader(httpContext.Response.Body).ReadToEndAsync();
                httpContext.Response.Body.Seek(0, SeekOrigin.Begin);

                Log.ForContext("RequestBody", requestBody)
                .ForContext("ResponseBody", responseBody)
                .Debug("Response information {RequestMethod} {RequestPath} {statusCode}", httpContext.Request.Method, httpContext.Request.Path, httpContext.Response.StatusCode);

                await responseBodyMemoryStream.CopyToAsync(originalResponseBodyReference);
            }
        }
        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            string requestBody = "";

            HttpRequestRewindExtensions.EnableBuffering(httpContext.Request);
            Stream body = httpContext.Request.Body;

            byte[] buffer = new byte[Convert.ToInt32(httpContext.Request.ContentLength)];
            await httpContext.Request.Body.ReadAsync(buffer, 0, buffer.Length);

            requestBody = Encoding.UTF8.GetString(buffer);
            body.Seek(0, SeekOrigin.Begin);
            httpContext.Request.Body = body;

            try
            {
                await _next(httpContext);

                if (httpContext.Response.StatusCode == (int)System.Net.HttpStatusCode.InternalServerError)
                {
                    Log.ForContext("RequestHeaders", httpContext.Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()), destructureObjects: true)
                    .ForContext("RequestBody", requestBody)
                    .Error("Request information {RequestMethod} {RequestPath} {StatusCode}", httpContext.Request.Method, httpContext.Request.Path, httpContext.Response.StatusCode);
                }
                else
                {
                    Log.ForContext("RequestHeaders", httpContext.Request.Headers.ToDictionary(h => h.Key, h => h.Value.ToString()), destructureObjects: true)
                    .ForContext("RequestBody", requestBody)
                    .Debug("Request information {RequestMethod} {RequestPath} {StatusCode}", httpContext.Request.Method, httpContext.Request.Path, httpContext.Response.StatusCode);
                }
            }
            catch (Exception exception)
            {
                Guid errorId = Guid.NewGuid();

                Log.ForContext("Type", "Error")
                .ForContext("Exception", exception, destructureObjects: true)
                .Error(exception, exception.Message + ". {@errorId}", errorId);

                var result = JsonConvert.SerializeObject(new { error = "Sorry, an unexpected error has occurred", errorId = errorId });
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.StatusCode  = 500;
                await httpContext.Response.WriteAsync(result);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Capture JSON request dari HTTP context
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private async Task <string> FormatRequest(HttpRequest request)
        {
            HttpRequestRewindExtensions.EnableBuffering(request);
            var body = request.Body;

            byte[] buffer = new byte[Convert.ToInt32(request.ContentLength)];
            await request.Body.ReadAsync(buffer, 0, buffer.Length);

            string requestBody = Encoding.UTF8.GetString(buffer);

            requestBody = RemoveLFCR(requestBody);
            body.Seek(0, SeekOrigin.Begin);
            request.Body = body;
            return(requestBody);
        }
Esempio n. 9
0
        private async Task <string> ReadRequestBody(HttpRequest request)
        {
            HttpRequestRewindExtensions.EnableBuffering(request);
            // hiddenString = number.Substring(number.Length - 4).PadLeft(number.Length, '*');
            var body   = request.Body;
            var buffer = new byte[Convert.ToInt32(request.ContentLength)];
            await request.Body.ReadAsync(buffer, 0, buffer.Length);

            string requestBody = Encoding.UTF8.GetString(buffer);

            body.Seek(0, SeekOrigin.Begin);
            request.Body = body;

            return($"{requestBody}");
        }
        public async Task <string> GetRequestBodyAsync(HttpRequest request)
        {
            string strRequestBody = "";

            // IMPORTANT: Ensure the requestBody can be read multiple times.
            HttpRequestRewindExtensions.EnableBuffering(request);

            // IMPORTANT: Leave the body open so the next middleware can read it.
            using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true))
            {
                strRequestBody = await reader.ReadToEndAsync();

                // IMPORTANT: Reset the request body stream position so the next middleware can read it
                request.Body.Position = 0;
            }

            return(strRequestBody);
        }
Esempio n. 11
0
        public async Task <ActionResult> SaveReplay(long game_id)
        {
            // Allows using several time the stream in ASP.Net Core
            HttpRequestRewindExtensions.EnableBuffering(Request);

            // Arguments: Stream, Encoding, detect encoding, buffer size
            // AND, the most important: keep stream opened
            int size = (int)Request.ContentLength;
            var b    = new byte[size];

            size = await Request.Body.ReadAsync(b, 0, size);

            // Rewind, so the core is not lost when it looks the body for the request
            Request.Body.Position = 0;

            await System.IO.File.WriteAllBytesAsync("replays/" + game_id + ".zip", b);

            return(Ok());
        }
        /// <summary>
        /// Returns Request Body string from Body stream
        /// </summary>
        /// <param name="request"></param>
        /// <returns>string</returns>
        public static string GetBodyString(this HttpRequest request)
        {
            HttpRequestRewindExtensions.EnableBuffering(request);

            var bodyString = string.Empty;

            using (var memoryReader = new MemoryStream())
                using (var reader = new StreamReader(memoryReader))
                {
                    request.Body.Position = 0;
                    request.Body.CopyToAsync(memoryReader);
                    memoryReader.Position = 0;
                    memoryReader.Seek(0, SeekOrigin.Begin);
                    bodyString            = reader.ReadToEndAsync().GetAwaiter().GetResult();
                    request.Body.Position = 0;
                }

            return(bodyString);
        }
Esempio n. 13
0
        /// <summary>
        /// Is valid request.
        /// </summary>
        /// <typeparam name="TModel">The request model</typeparam>
        /// <param name="httpRequest">The http request</param>
        /// <param name="condition">the valid condition</param>
        /// <returns>true/false based on the evaluation of the condition</returns>
        internal async static Task <bool> IsValid <TModel>(this HttpRequest httpRequest, Func <TModel, bool> condition)
        {
            // Allows using several time the stream in ASP.Net Core

            HttpRequestRewindExtensions.EnableBuffering(httpRequest);

            using (MemoryStream m = new MemoryStream())
            {
                await httpRequest.Body.CopyToAsync(m);

                var bodyString = Encoding.UTF8.GetString(m.ToArray());

                httpRequest.Body.Position = 0;

                var model = JsonConvert.DeserializeObject <TModel>(bodyString);

                return(condition(model));
            }
        }
Esempio n. 14
0
        //TODO: evaluate if using OrderCloudIntegrationException for errors works as expected
        protected override async Task <AuthenticateResult> HandleAuthenticateAsync()
        {
            Require.DoesNotExist(Options.HashKey, async() => await Task.FromResult(AuthenticateResult.Fail(AUTH_FAIL_MSG)));
            Require.DoesNotExist(Context.Request.Headers.ContainsKey(OC_HASH), async() => await Task.FromResult(AuthenticateResult.Fail(AUTH_FAIL_MSG)));
            Require.DoesNotExist(Context.Request.Headers[OC_HASH].FirstOrDefault(), async() => await Task.FromResult(AuthenticateResult.Fail(AUTH_FAIL_MSG)));

            var hash_header = Context.Request.Headers[OC_HASH].FirstOrDefault();

            // alternative to Context.Request.EnableRewind() which is no longer available
            // allows us to set Request Body position back to 0
            HttpRequestRewindExtensions.EnableBuffering(Context.Request);

            try
            {
                Require.ThatHashMatches(hash_header, Options.HashKey, Context.Request.Body, async() => await Task.FromResult(AuthenticateResult.Fail(HASH_MATCH_FAIL)));
                var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(AUTH_SCHEME)), AUTH_SCHEME);
                return(await Task.FromResult(AuthenticateResult.Success(ticket)));
            }
            finally
            {
                Context.Request.Body.Position = 0;
            }
        }
        public async Task Invoke(HttpContext context)
        {
            HttpRequestRewindExtensions.EnableBuffering(context.Request);

            var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
            await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);

            var requestBody = Encoding.UTF8.GetString(buffer);

            context.Request.Body.Seek(0, SeekOrigin.Begin);

            var builder = new StringBuilder(Environment.NewLine);

            foreach (var header in context.Request.Headers)
            {
                builder.AppendLine($"{header.Key}:{header.Value}");
            }

            builder.AppendLine($"Request body:{requestBody}");

            _logger.LogInformation(builder.ToString( ));

            await _next(context);
        }
Esempio n. 16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }
            var request = context.HttpContext.Request;

            if (!request.Body.CanSeek)
            {
                HttpRequestRewindExtensions.EnableBuffering(request);
                await StreamHelperExtensions.DrainAsync(request.Body, CancellationToken.None);

                request.Body.Seek(0L, SeekOrigin.Begin);
            }

            using (TextReader textReader = context.ReaderFactory(request.Body, encoding))
            {
                var modelType = context.ModelType;
                if (modelType.IsArray)
                {
                    var itemType = modelType.GetElementType();
                    var arr      = new ArrayList();
                    while (true)
                    {
                        var line = textReader.ReadLine();
                        if (string.IsNullOrEmpty(line))
                        {
                            break;
                        }
                        var obj = GetModel(line, itemType);
                        arr.Add(obj);
                    }
                    var modelList = arr.ToArray(itemType);
                    return(await InputFormatterResult.SuccessAsync(modelList));
                }
                else if (typeof(IEnumerable).IsAssignableFrom(modelType))
                {
                    var   itemType  = modelType.GenericTypeArguments[0];
                    var   listType  = typeof(List <>).MakeGenericType(itemType);
                    IList modelList = (IList)Activator.CreateInstance(listType);
                    while (true)
                    {
                        var line = textReader.ReadLine();
                        if (string.IsNullOrEmpty(line))
                        {
                            break;
                        }
                        var obj = GetModel(line, itemType);
                        modelList.Add(obj);
                    }
                    return(await InputFormatterResult.SuccessAsync(modelList));
                }
                else
                {
                    var obj = GetModel(textReader.ReadLine(), modelType);
                    return(await InputFormatterResult.SuccessAsync(obj));
                }
            }
        }