示例#1
0
        private bool ValidateRequest(
            string httpMethod,
            UserLoan value,
            object param1,
            out List <string> validationFailureMessages)
        {
            bool result = true;

            validationFailureMessages = new List <string>();

            if (HttpMethods.IsPost(httpMethod))
            {
                if (value.Id != 0)
                {
                    result = false;
                    validationFailureMessages.Add(Constants.Message.ValidationFailedIdShouldBeNull);
                }
            }

            else if (HttpMethods.IsPut(httpMethod))
            {
                if (value.Id.ToString() != param1.ToString())
                {
                    result = false;
                    validationFailureMessages.Add(Constants.Message.ValidationFailedIdsShouldMatch);
                }
            }

            _appLogger.LogError($"UserLoanController::Validate(httpMethod: {httpMethod}, <value>, param1: {param1}) >> Result = {result}.");
            return(result);
        }
示例#2
0
        public static async Task <(bool Exists, StringValues Value)> TryGetParamAsync(this HttpRequest httpRequest, string key, CancellationToken cancellationToken)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var hasForm = (HttpMethods.IsPost(httpRequest.Method) ||
                           HttpMethods.IsPut(httpRequest.Method) ||
                           HttpMethods.IsDelete(httpRequest.Method) ||
                           HttpMethods.IsPatch(httpRequest.Method)) &&
                          httpRequest.HasFormContentType;

            var exists = httpRequest.Query.TryGetValue(key, out var value);

            if (!exists && hasForm)
            {
                var form = await httpRequest.ReadFormAsync(cancellationToken).ConfigureAwaitFalse();

                exists = form.TryGetValue(key, out value);
            }

            return(exists, value);
        }
示例#3
0
        public static async Task <JsonApiRequest> FromHttpRequestAsync(HttpRequest request)
        {
            var body = await new StreamReader(request.Body).ReadToEndAsync();

            return(new JsonApiRequest(GetUserName(), GetAction(), body, ParseDictionary(request.Headers), ParseDictionary(request.Query)));

            RequestAction GetAction() =>
            (HttpMethods.IsGet(request.Method)) ? RequestAction.Get :
            (HttpMethods.IsPost(request.Method) || HttpMethods.IsPut(request.Method) || HttpMethods.IsPatch(request.Method)) ? RequestAction.Save :
            (HttpMethods.IsDelete(request.Method)) ? RequestAction.Delete :
            throw new Exception($"Unsupported method: {request.Method}");

            string GetUserName()
            {
                try
                {
                    return(request.HttpContext.User.Identity.Name);
                }
                catch
                {
                    return(null);
                }
            }

            Dictionary <string, StringValues> ParseDictionary(IEnumerable <KeyValuePair <string, StringValues> > collection) =>
            collection
            .GroupBy(item => item.Key)
            .ToDictionary(
                grp => grp.Key,
                grp => new StringValues(grp.SelectMany(item => item.Value).ToArray()));
        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            try
            {
                _requestMethod    = context.HttpContext.Request.Method;
                _apiRequestMethod = context.HttpContext.Request.Headers["ApiRequestMethod"].FirstOrDefault() ?? _requestMethod ?? "GET";

                _cacheReadEnabled   = HttpMethods.IsGet(_apiRequestMethod) || HttpMethods.IsPost(_apiRequestMethod);
                _cacheUpdateEnabled = HttpMethods.IsPut(_apiRequestMethod) ||
                                      HttpMethods.IsPatch(_apiRequestMethod) || HttpMethods.IsDelete(_apiRequestMethod) ||
                                      (HttpMethods.IsPost(_apiRequestMethod) &&
                                       _updateMethodStartNames.Any(x => ((ControllerActionDescriptor)context.ActionDescriptor).ActionName.ToLower().StartsWith(x)));

                if (!_cacheUpdateEnabled)
                {
                    _cacheKey       = _cacheService.CreateCacheKey(context.HttpContext.Request.Path, _modelType.Name);
                    _cacheKeyExists = _cacheService.ContainsKey(_cacheKey);
                }

                _cacheTypeExists = _cacheService.ContainsKeyType(_modelType.Name);
            }
            catch (Exception ex)
            {
                GeneralContext.Logger.Error(ex.GetApiMessageInfo());
                _cacheKeyExists = false;
            }

            if ((_cacheReadEnabled && !_cacheKeyExists) || _cacheUpdateEnabled)
            {
                await next();
            }
        }
示例#5
0
        private bool TryGetManagementHandler(HttpContext httpContext, IRequestDetails?requestDetails, out IRequestHandler?result)
        {
            if (requestDetails == null || !requestDetails.IsCommandRequest(out var commandName))
            {
                result = null;
                return(false);
            }

            result = requestDetails.HttpMethod switch
            {
                _ when HttpMethods.IsGet(requestDetails.HttpMethod) &&
                StringComparer.OrdinalIgnoreCase.Equals(commandName, Constants.HeaderValues.ConfigureCommandName)
                => httpContext.RequestServices.GetService <ConfigureCommandGetHandler>(),

                _ when HttpMethods.IsPut(requestDetails.HttpMethod) &&
                StringComparer.OrdinalIgnoreCase.Equals(commandName, Constants.HeaderValues.ConfigureCommandName)
                => httpContext.RequestServices.GetService <ConfigureCommandPutHandler>(),

                _ when HttpMethods.IsPost(requestDetails.HttpMethod) &&
                StringComparer.OrdinalIgnoreCase.Equals(commandName, Constants.HeaderValues.ResetCounterCommandName)
                => httpContext.RequestServices.GetService <ResetCounterCommandHandler>(),

                _ when HttpMethods.IsPost(requestDetails.HttpMethod) &&
                StringComparer.OrdinalIgnoreCase.Equals(commandName, Constants.HeaderValues.ResetConfigurationCommandName)
                => httpContext.RequestServices.GetService <ResetConfigurationCommandHandler>(),

                _ => null
            };

            return(result != null);
        }
    }
示例#6
0
        public static bool TryGetParam(this HttpRequest httpRequest, string key, out StringValues value)
        {
            if (httpRequest == null)
            {
                throw new ArgumentNullException(nameof(httpRequest));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var hasForm = (HttpMethods.IsPost(httpRequest.Method) ||
                           HttpMethods.IsPut(httpRequest.Method) ||
                           HttpMethods.IsDelete(httpRequest.Method)) &&
                          httpRequest.HasFormContentType;

            if (!hasForm)
            {
                return(httpRequest.Query.TryGetValue(key, out value));
            }

            return
                (httpRequest.Form.TryGetValue(key, out value) ||
                 httpRequest.Query.TryGetValue(key, out value));
        }
        private async Task InvokeApi(HttpContext httpContext)
        {
            httpContext.Request.Headers.TryGetValue("Prefer", out StringValues preferHeader);
            OeRequestHeaders headers = OeRequestHeaders.Parse(httpContext.Request.Headers["Accept"], preferHeader);

            Uri baseUri    = UriHelper.GetBaseUri(httpContext.Request);
            Uri requestUri = UriHelper.GetUri(httpContext.Request);

            if (HttpMethods.IsGet(httpContext.Request.Method))
            {
                var parser = new OeParser(baseUri, EdmModel, GetModelBoundProvider(httpContext), OeParser.ServiceProvider);
                await parser.ExecuteGetAsync(requestUri, new OeHttpRequestHeaders(headers, httpContext.Response),
                                             httpContext.Response.Body, httpContext.RequestAborted).ConfigureAwait(false);
            }
            else if (HttpMethods.IsPost(httpContext.Request.Method) ||
                     HttpMethods.IsPut(httpContext.Request.Method) ||
                     HttpMethods.IsPatch(httpContext.Request.Method) ||
                     HttpMethods.IsDelete(httpContext.Request.Method))
            {
                ODataUri odataUri = OeParser.ParseUri(EdmModel, baseUri, requestUri, OeParser.ServiceProvider);
                if (odataUri.Path.LastSegment is OperationImportSegment)
                {
                    var parser = new OeParser(baseUri, EdmModel, GetModelBoundProvider(httpContext), OeParser.ServiceProvider);
                    await parser.ExecuteOperationAsync(odataUri, new OeHttpRequestHeaders(headers, httpContext.Response),
                                                       httpContext.Request.Body, httpContext.Response.Body, httpContext.RequestAborted).ConfigureAwait(false);
                }
                else
                {
                    httpContext.Response.ContentType = httpContext.Request.ContentType;
                    var batchParser = new OeBatchParser(baseUri, EdmModel, OeParser.ServiceProvider);
                    await batchParser.ExecuteOperationAsync(requestUri, httpContext.Request.Body, httpContext.Response.Body,
                                                            httpContext.Request.ContentType, httpContext.Request.Method, httpContext.RequestAborted).ConfigureAwait(false);
                }
            }
        }
        private static HttpMethod ParseHttpMethod(string method)
        {
            if (HttpMethods.IsGet(method))
            {
                return(HttpMethod.Get);
            }
            if (HttpMethods.IsPost(method))
            {
                return(HttpMethod.Post);
            }
            if (HttpMethods.IsPut(method))
            {
                return(HttpMethod.Put);
            }
            if (HttpMethods.IsDelete(method))
            {
                return(HttpMethod.Delete);
            }
            if (HttpMethods.IsOptions(method))
            {
                return(HttpMethod.Options);
            }

            return(new HttpMethod(method));
        }
示例#9
0
        public void Inspect(RequestAnalysisContext context, CancellationToken cancellationToken)
        {
            var method = context.Request.Method;

            if (!HttpMethods.IsGet(method) &&
                !HttpMethods.IsHead(method) &&
                !HttpMethods.IsOptions(method) &&
                !HttpMethods.IsPost(method) &&
                !HttpMethods.IsDelete(method) &&
                !HttpMethods.IsPut(method) &&
                !HttpMethods.IsPatch(method) &&
                !HttpMethods.IsConnect(method)
                )
            {
                // TRACE must be disabled
                if (HttpMethods.IsTrace(method))
                {
                    context.ReportDiagnostic(new Diagnostic(RuleTrace, Location.Method));
                    return;
                }

                // unknown method
                context.ReportDiagnostic(new Diagnostic(Rule, Location.Method));

                // Apache directory listing exploit
                if (method.Equals("GETS", StringComparison.OrdinalIgnoreCase))
                {
                    context.ReportDiagnostic(new Diagnostic(RuleGets, Location.Method));
                }
            }
        }
示例#10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns>Cache Validation Status</returns>
        public static CacheValidationStatus GetCacheValidationStatus(this HttpRequest request)
        {
            var typedHeaders = request.GetTypedHeadersWithCaching();

            if (HttpMethods.IsGet(request.Method))
            {
                if (typedHeaders.IfModifiedSince.HasValue)
                {
                    return(CacheValidationStatus.GetIfModifiedSince);
                }
                if (typedHeaders.IfNoneMatch != null && typedHeaders.IfNoneMatch.Count > 0)
                {
                    return(CacheValidationStatus.GetIfNoneMatch);
                }
            }

            if (HttpMethods.IsPut(request.Method))
            {
                if (typedHeaders.IfUnmodifiedSince.HasValue)
                {
                    return(CacheValidationStatus.PutIfUnModifiedSince);
                }
                if (typedHeaders.IfMatch != null && typedHeaders.IfMatch.Count > 0)
                {
                    return(CacheValidationStatus.PutIfMatch);
                }
            }

            return(CacheValidationStatus.None);
        }
        public virtual Task <IActionResult> HandleAsync(HttpRequest request)
        {
            if (HttpMethods.IsGet(request.Method))
            {
                return(HandleGetAsync(request));
            }

            if (HttpMethods.IsPost(request.Method))
            {
                return(HandlePostAsync(request));
            }

            if (HttpMethods.IsPut(request.Method))
            {
                return(HandlePutAsync(request));
            }

            if (HttpMethods.IsPatch(request.Method))
            {
                return(HandlePatchAsync(request));
            }

            if (HttpMethods.IsDelete(request.Method))
            {
                return(HandleDeleteAsync(request));
            }

            return(methodNotAllowed);
        }
示例#12
0
 private static HttpMethod GetMethod(string method)
 {
     if (HttpMethods.IsDelete(method))
     {
         return(HttpMethod.Delete);
     }
     if (HttpMethods.IsGet(method))
     {
         return(HttpMethod.Get);
     }
     if (HttpMethods.IsHead(method))
     {
         return(HttpMethod.Head);
     }
     if (HttpMethods.IsOptions(method))
     {
         return(HttpMethod.Options);
     }
     if (HttpMethods.IsPost(method))
     {
         return(HttpMethod.Post);
     }
     if (HttpMethods.IsPut(method))
     {
         return(HttpMethod.Put);
     }
     if (HttpMethods.IsTrace(method))
     {
         return(HttpMethod.Trace);
     }
     return(new HttpMethod(method));
 }
        private string OperationDescription(OperationFilterContext context)
        {
            var resourceName = context.MethodInfo.DeclaringType?.GetGenericArguments().Single().Name;
            var methodName   = context.ApiDescription.HttpMethod;

            if (HttpMethods.IsGet(methodName))
            {
                if (!context.MethodInfo.GetParameters().Any())
                {
                    return($"Retrieve all {resourceName}");
                }
                else
                {
                    return($"Retrieve {resourceName}");
                }
            }

            if (HttpMethods.IsPost(methodName))
            {
                return($"Create {resourceName}");
            }

            if (HttpMethods.IsPut(methodName))
            {
                return($"Replace {resourceName}");
            }

            if (HttpMethods.IsDelete(methodName))
            {
                return($"Delete {resourceName}");
            }

            return(methodName);
        }
示例#14
0
        public async Task InvokeAsync(HttpContext context)
        {
            var method = context.Request.Method;

            if (HttpMethods.IsPost(method) || HttpMethods.IsPut(method) || HttpMethods.IsDelete(method))
            {
                try {
                    await antiforgery.ValidateRequestAsync(context);
                } catch (AntiforgeryValidationException) {
                    throw new AuthorizationException();
                }
            }

            // if route is an action route and token was validated successfully, create new token
            var tokens = antiforgery.GetAndStoreTokens(context);

            context.Response.Cookies.Append(
                Environment.GetEnvironmentVariable("XSRF_COOKIE"),
                tokens.RequestToken,
                new CookieOptions()
            {
                MaxAge   = TimeSpan.FromMinutes(cookieLifetime),
                HttpOnly = false,
                Secure   = Environment.GetEnvironmentVariable("APP_ENV") != "local"
            }
                );

            await next(context);
        }
示例#15
0
 public bool IsPush()
 {
     return(HttpMethods
            .IsPut(Method) &&
            _requestHeaders.ContentType != null &&
            _requestHeaders.ContentType
            .IsSubsetOf(PushContentType));
 }
        public async Task <IActionResult> SaveProfile(
            [BindRequired, FromQuery] string profileId,
            [BindRequired, FromQuery] Iri activityId,
            [BindRequired, FromHeader(Name = "Content-Type")] string contentType,
            [BindRequired, FromBody] byte[] body,
            [FromQuery] Guid?registration       = null,
            CancellationToken cancellationToken = default)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var profile = await _mediator.Send(new GetActivityProfileQuery()
            {
                ActivityId   = activityId,
                ProfileId    = profileId,
                Registration = registration
            }, cancellationToken);

            if (Request.TryConcurrencyCheck(profile?.Document.Checksum, profile?.Document.LastModified, out int statusCode))
            {
                return(StatusCode(statusCode));
            }

            if (profile != null)
            {
                // Optimistic Concurrency
                if (HttpMethods.IsPut(Request.Method))
                {
                    return(Conflict());
                }

                await _mediator.Send(new UpdateActivityProfileCommand()
                {
                    ProfileId    = profileId,
                    ActivityId   = activityId,
                    Content      = body,
                    ContentType  = contentType,
                    Registration = registration
                }, cancellationToken);
            }
            else
            {
                await _mediator.Send(new CreateActivityProfileCommand()
                {
                    ProfileId    = profileId,
                    ActivityId   = activityId,
                    Content      = body,
                    ContentType  = contentType,
                    Registration = registration
                }, cancellationToken);
            }

            return(NoContent());
        }
        public bool Matches(RouteData routeData, string httpVerb, HttpRequest request)
        {
            var controller = (string)routeData.Values["controller"];
            var action     = (string)routeData.Values["action"];

            return(HttpMethods.IsPut(httpVerb) &&
                   controller.ToLowerInvariant() == "questions" &&
                   string.IsNullOrWhiteSpace(action) &&
                   !routeData.Values.ContainsKey("id"));
        }
示例#18
0
        public async Task <IActionResult> ExecuteAsync(HttpRequest request)
        {
            try
            {
                using (var cn = GetConnection())
                {
                    Account = await AuthenticateAsync(cn, request);

                    if (Account == null)
                    {
                        throw new Exception("Request not validated");
                    }

                    if (HttpMethods.IsGet(request.Method))
                    {
                        var id     = GetKey(request);
                        var result = await GetAsync(cn, id);

                        return(new OkObjectResult(result));
                    }
                    else
                    {
                        if (HttpMethods.IsPost(request.Method))
                        {
                            var model = await request.DeserializeAsync <TModel>();

                            var id = await CreateAsync(cn, model);

                            return(new OkObjectResult(id));
                        }
                        else if (HttpMethods.IsPut(request.Method))
                        {
                            var model = await request.DeserializeAsync <TModel>();
                            await UpdateAsync(cn, model);

                            return(new OkResult());
                        }
                        else if (HttpMethods.IsDelete(request.Method))
                        {
                            var id = GetKey(request);
                            await DeleteAsync(cn, id);

                            return(new OkResult());
                        }

                        return(new BadRequestObjectResult($"Unsupported method: {request.Method}"));
                    }
                }
            }
            catch (Exception exc)
            {
                Logger.LogError(exc, exc.Message);
                return(new BadRequestObjectResult(exc.Message));
            }
        }
示例#19
0
 private bool AcceptRequestUpdateUser(string objectId)
 {
     if (
         HttpMethods.IsPut(_httpContext.HttpContext.Request.Method) &&
         String.Equals(_httpContext.HttpContext.Request.RouteValues["Action"] as string, "UpdateUser")
         )
     {
         var expression = String.Equals(_httpContext.HttpContext.Request.RouteValues["userId"] as string, objectId);
         return(BuildBoolExpression(expression, _stringBuilderRegular, "User ID does not match the one on requested URL!"));
     }
     return(true);
 }
示例#20
0
        static bool SetupMethodAndContent(HttpRequest request, HttpRequestMessage proxiedMessage)
        {
            var hasContent    = false;
            var requestMethod = request.Method;

            // Try to use the static HttpMethods rather than creating a new one.
            if (HttpMethods.IsGet(requestMethod))
            {
                proxiedMessage.Method = HttpMethod.Get;
            }
            else if (HttpMethods.IsHead(requestMethod))
            {
                proxiedMessage.Method = HttpMethod.Head;
            }
            else if (HttpMethods.IsDelete(requestMethod))
            {
                proxiedMessage.Method = HttpMethod.Delete;
            }
            else if (HttpMethods.IsTrace(requestMethod))
            {
                proxiedMessage.Method = HttpMethod.Trace;
            }
            else
            {
                hasContent = true;

                if (HttpMethods.IsPost(requestMethod))
                {
                    proxiedMessage.Method = HttpMethod.Post;
                }
                else if (HttpMethods.IsOptions(requestMethod))
                {
                    proxiedMessage.Method = HttpMethod.Options;
                }
                else if (HttpMethods.IsPut(requestMethod))
                {
                    proxiedMessage.Method = HttpMethod.Put;
                }
                else if (HttpMethods.IsPatch(requestMethod))
                {
                    proxiedMessage.Method = HttpMethod.Patch;
                }
                else
                {
                    proxiedMessage.Method = new HttpMethod(request.Method);
                }

                proxiedMessage.Content = new StreamContent(request.Body);
            }

            return(hasContent);
        }
        /// <summary>
        /// Return a corresponding VerbsHttpMethod with the verb used in the request.
        /// </summary>
        /// <param name="context">ActionExecutingContext</param>
        /// <returns>Return VerbsHttpMethod corresponding to the request.</returns>
        public static VerbsHttpMethod GetVerbs(this ActionExecutingContext context)
        {
            var method = context.HttpContext.Request.Method;

            if (HttpMethods.IsGet(method))
            {
                return(VerbsHttpMethod.Get);
            }

            if (HttpMethods.IsPost(method))
            {
                return(VerbsHttpMethod.Post);
            }

            if (HttpMethods.IsDelete(method))
            {
                return(VerbsHttpMethod.Delete);
            }

            if (HttpMethods.IsPut(method))
            {
                return(VerbsHttpMethod.Put);
            }

            if (HttpMethods.IsHead(method))
            {
                return(VerbsHttpMethod.Head);
            }

            if (HttpMethods.IsOptions(method))
            {
                return(VerbsHttpMethod.Options);
            }

            if (HttpMethods.IsPatch(method))
            {
                return(VerbsHttpMethod.Patch);
            }

            if (HttpMethods.IsTrace(method))
            {
                return(VerbsHttpMethod.Trace);
            }

            if (HttpMethods.IsConnect(method))
            {
                return(VerbsHttpMethod.Connect);
            }

            throw new HttpMethodNotFoundException($"Could not find the HttpMethod '{method}'");
        }
示例#22
0
        /// <summary>
        /// Converts the given HTTP method (usually obtained from <see cref="HttpRequest.Method"/>)
        /// into the corresponding <see cref="HttpMethod"/> static instance.
        /// </summary>
        public static HttpMethod GetHttpMethod(string method)
        {
            if (HttpMethods.IsGet(method))
            {
                return(HttpMethod.Get);
            }

            if (HttpMethods.IsPost(method))
            {
                return(HttpMethod.Post);
            }

            if (HttpMethods.IsPut(method))
            {
                return(HttpMethod.Put);
            }

            if (HttpMethods.IsDelete(method))
            {
                return(HttpMethod.Delete);
            }

            if (HttpMethods.IsOptions(method))
            {
                return(HttpMethod.Options);
            }

            if (HttpMethods.IsHead(method))
            {
                return(HttpMethod.Head);
            }

            if (HttpMethods.IsPatch(method))
            {
                return(HttpMethod.Patch);
            }

            if (HttpMethods.IsTrace(method))
            {
                return(HttpMethod.Trace);
            }

            // NOTE: Proxying "CONNECT" is not supported (by design!)
            //if (HttpMethods.IsConnect(method))
            //{
            //    return new HttpMethod("CONNECT");
            //}

            throw new InvalidOperationException($"Unsupported request method '{method}'.");
        }
示例#23
0
        /// <summary>
        /// Handle the current HTTP request.
        /// </summary>
        /// <param name="context">Current <see cref="HttpContext"/>.</param>
        /// <returns>The <see cref="Task"/> that represents the asynchronous process.</returns>
        public async Task HandleAsync(HttpContext context)
        {
            foreach (var validator in _validators)
            {
                var validationResult = await validator.ValidateAsync(context);

                if (!validationResult.Succeeded)
                {
                    await SetHttpContextResponse(context, validationResult.ResponseMessage);

                    return;
                }
            }

            var requestMessage = new HttpRequestMessage();
            var requestMethod  = context.Request.Method;

            if (HttpMethods.IsPost(requestMethod) ||
                HttpMethods.IsPut(requestMethod))
            {
                requestMessage.Content = new StreamContent(context.Request.Body);
            }

            foreach (var header in context.Request.Headers)
            {
                if (!requestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()))
                {
                    requestMessage.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
                }
            }

            var requestUri = _uriBuilder.Build(context);

            requestMessage.Headers.Host = requestUri.Host;
            requestMessage.RequestUri   = requestUri;
            requestMessage.Method       = new HttpMethod(requestMethod);

            try
            {
                using (var responseMessage = await _httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
                {
                    await SetHttpContextResponse(context, responseMessage);
                }
            }
            catch (OperationCanceledException)
            {
                await SetHttpContextResponse(context, new HttpResponseMessage(HttpStatusCode.GatewayTimeout));
            }
        }
示例#24
0
        public async Task Invoke(HttpContext context, IIdentityService identityService)
        {
            var method = context.Request.Method;

            _telemetry.TrackTrace(new TraceTelemetry(identityService.GetScope(), SeverityLevel.Information));

            if (HttpMethods.IsPost(method) || HttpMethods.IsPut(method) || HttpMethods.IsPatch(method))
            {
                var body = await FormatRequestBody(context.Request);

                _telemetry.TrackTrace(new TraceTelemetry(body, SeverityLevel.Information));
            }

            await _next(context);
        }
示例#25
0
        public async Task Invoke(HttpContext context, IIdentityService identityService)
        {
            var method    = context.Request.Method;
            var telemetry = new TelemetryClient(new TelemetryConfiguration(_applicationInsights.InstrumentationKey));

            telemetry.TrackTrace(new TraceTelemetry(identityService.GetScope(), SeverityLevel.Information));

            if (HttpMethods.IsPost(method) || HttpMethods.IsPut(method) || HttpMethods.IsPatch(method))
            {
                var body = await FormatRequestBody(context.Request);

                telemetry.TrackTrace(new TraceTelemetry(body, SeverityLevel.Information));
            }

            await _next(context);
        }
示例#26
0
        /// <summary>
        /// Takes a snapshot of the current request body.
        /// </summary>
        /// <returns></returns>
        internal async Task SnapRequestBody()
        {
            var method = HttpContext.Request.Method;

            HttpContext.Request.EnableBuffering();
            // Only if we are dealing with POST or PUT, GET and others shouldn't have a body.
            if (HttpContext.Request.Body.CanRead && (HttpMethods.IsPost(method) || HttpMethods.IsPut(method) || HttpMethods.IsPatch(method)))
            {
                // Leave stream open so next middleware can read it.
                using var reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, bufferSize: 512, leaveOpen: true);
                RequestBody      = await reader.ReadToEndAsync();

                // Reset stream position, so next middleware can read it.
                HttpContext.Request.Body.Seek(0, SeekOrigin.Begin);
            }
        }
示例#27
0
        public static void Main(string[] args)
        {
            new WebHostBuilder()
            .UseKestrel(options =>
            {
                options.Listen(IPAddress.Any, 5000);
                options.Listen(IPAddress.Any, 5001, listenOptions =>
                {
                    listenOptions.UseHttps("testCert.pfx", "testPassword");
                });
                options.Limits.MaxRequestBodySize = null;
            })
            .Configure(app => app.Run(async context =>
            {
                if (HttpMethods.IsPut(context.Request.Method))
                {
                    long bytesRead = 0;

                    var reader = context.Request.BodyReader;
                    while (true)
                    {
                        var result = await reader.ReadAsync();
                        bytesRead += result.Buffer.Length;
                        reader.AdvanceTo(result.Buffer.End);
                        if (result.IsCompleted)
                        {
                            break;
                        }
                    }

                    var payload = Encoding.UTF8.GetBytes(bytesRead.ToString());
                    context.Response.StatusCode    = 200;
                    context.Response.ContentType   = "text/plain";
                    context.Response.ContentLength = payload.Length;
                    await context.Response.Body.WriteAsync(payload, 0, payload.Length);
                }
                else
                {
                    context.Response.StatusCode    = 200;
                    context.Response.ContentType   = "text/plain";
                    context.Response.ContentLength = _payloadLength;
                    await context.Response.Body.WriteAsync(_payload, 0, _payloadLength);
                }
            }))
            .Build()
            .Run();
        }
示例#28
0
        public async Task Handle(ITable table, string id)
        {
            if (HttpMethods.IsGet(Request.Method) && !string.IsNullOrEmpty(id))
            {
                var records = await _databaseRepository.GetItemAsync(table, id);
                await JsonResponse(records);
            }
            else if (HttpMethods.IsGet(Request.Method))
            {
                var records = await _databaseRepository.GetItemsAsync(table, 1, int.MaxValue);
                await JsonResponse(records);
            }
            else if (HttpMethods.IsPut(Request.Method) && !string.IsNullOrEmpty(id))
            {
                using (var reader = new StreamReader(Request.Body))
                {
                    var json       = reader.ReadToEnd();
                    var dictionary = DeserializeJson(json);
                    await _databaseRepository.UpdateItemAsync(table, id, dictionary);

                    HttpNoContentResponse();
                }
            }
            else if (HttpMethods.IsDelete(Request.Method) && !string.IsNullOrEmpty(id))
            {
                await _databaseRepository.DeleteItemAsync(table, id);

                HttpNoContentResponse();
            }
            else if (HttpMethods.IsPost(Request.Method))
            {
                using (var reader = new StreamReader(Request.Body))
                {
                    var json       = reader.ReadToEnd();
                    var dictionary = DeserializeJson(json);
                    await _databaseRepository.InsertItemAsync(table, dictionary);

                    HttpNoContentResponse();
                }
            }
            else
            {
                await HttpNotFoundResponse();
            }
        }
示例#29
0
        /// <summary>
        /// Gets content from the PagerDuty API.
        /// </summary>
        /// <typeparam name="T">The Type to return (deserialized from the returned JSON).</typeparam>
        /// <param name="path">The path to return, including any query string.</param>
        /// <param name="getFromJson">The deserialize function.</param>
        /// <param name="httpMethod">The HTTP method to use for this API call.</param>
        /// <param name="data">Data to serialize for the request.</param>
        /// <param name="extraHeaders">Headers to add to the API request.</param>
        /// <returns>The deserialized content from the PagerDuty API.</returns>
        public async Task <T> GetFromPagerDutyAsync <T>(string path, Func <string, T> getFromJson, string httpMethod = "GET", object data = null, Dictionary <string, string> extraHeaders = null)
        {
            const string baseUrl = "https://api.pagerduty.com/";
            var          fullUri = baseUrl + path;

            using (MiniProfiler.Current.CustomTiming("http", fullUri, httpMethod))
            {
                var request = Http.Request(fullUri)
                              .AddHeader(HeaderNames.Accept, "application/vnd.pagerduty+json;version=2")
                              .AddHeader(HeaderNames.Authorization, "Token token=" + APIKey);

                if (extraHeaders != null)
                {
                    foreach (var h in extraHeaders.Keys)
                    {
                        request.AddHeader(h, extraHeaders[h]);
                    }
                }

                if ((HttpMethods.IsPost(httpMethod) || HttpMethods.IsPut(httpMethod)) && data != null)
                {
                    request.AddHeader(HeaderNames.ContentType, "application/json");
                    request.SendJson(data, JilOptions);
                }

                try
                {
                    var response = httpMethod switch
                    {
                        _ when HttpMethods.IsPut(httpMethod) => await request.ExpectString().PutAsync(),
                        _ when HttpMethods.IsPost(httpMethod) => await request.ExpectString().PostAsync(),
                        _ => await request.ExpectString().GetAsync(),
                    };

                    // TODO: We could make this streaming JSON parsing probably
                    return(getFromJson(response.Data));
                }
                catch (WebException e)
                {
                    // StackExchange.Utils lib is handling the logging load here
                    e.Log();
                    return(getFromJson(null));
                }
            }
        }
示例#30
0
        private RequestDelegate CreateRequestHandler(string requestMethod, Type requestModelType, bool hasIdSegment, int?id)
        {
            if (HttpMethods.IsGet(requestMethod))
            {
                if (hasIdSegment)
                {
                    return(GetType().GetMethod(nameof(CreateGetHandler))
                           .MakeGenericMethod(requestModelType)
                           .Invoke(this, new object[] { id }) as RequestDelegate);
                }
                else
                {
                    return(GetType().GetMethod(nameof(CreateGetAllHandler))
                           .MakeGenericMethod(requestModelType)
                           .Invoke(this, new object[] {}) as RequestDelegate);
                }
            }

            if (hasIdSegment)
            {
                return(null);
            }

            if (HttpMethods.IsPost(requestMethod))
            {
                return(GetType().GetMethod(nameof(CreateAddHandler))
                       .MakeGenericMethod(requestModelType)
                       .Invoke(this, new object[] {}) as RequestDelegate);
            }
            else if (HttpMethods.IsPut(requestMethod))
            {
                return(GetType().GetMethod(nameof(CreateUpdateHandler))
                       .MakeGenericMethod(requestModelType)
                       .Invoke(this, new object[] {}) as RequestDelegate);
            }
            else if (HttpMethods.IsDelete(requestMethod))
            {
                return(GetType().GetMethod(nameof(CreateDeleteHandler))
                       .MakeGenericMethod(requestModelType)
                       .Invoke(this, new object[] {}) as RequestDelegate);
            }

            return(null);
        }