public async Task Invoke(HttpContext context) { var memoryStream = new MemoryStream(); var bodyStream = context.Response.Body; context.Response.Body = memoryStream; await _next?.Invoke(context); var request = context.Request; var response = context.Response; if (!string.IsNullOrWhiteSpace(request.Headers["X-XHR-Referer"])) { context.Response.Cookies.Append("request_method", request.Method, new CookieOptions { HttpOnly = false }); if (context.Response.StatusCode == 301 || context.Response.StatusCode == 302) { var uri = new Uri(response.Headers["Location"]); if (uri.Host.Equals(request.Host.Value)) { response.Headers["X-XHR-Redirected-To"] = response.Headers["Location"]; } } } memoryStream.WriteTo(bodyStream); await bodyStream.FlushAsync(); memoryStream.Dispose(); bodyStream.Dispose(); }
public async Task Invoke(HttpContext context) { if (context.WebSockets.IsWebSocketRequest) { var webSocket = await context.WebSockets.AcceptWebSocketAsync(); var ct = context.RequestAborted; var json = await RecieveStringAsync(webSocket, ct); var command = JsonConvert.DeserializeObject <dynamic>(json); switch (command.Operation.ToString()) { case "CheckEmailConfirmationStatus": { await ProccessEmailConfirmation(context, webSocket, ct, command.Parameters.ToString()); break; } } } else if (context.Request.Path.Equals("/CheckEmailConfirmationStatus")) { { await _next?.Invoke(context); } } }
/// <summary> /// Invokes the middleware. /// </summary> /// <param name="httpContext">Encapsulates all HTTP-specific information about an individual HTTP request.</param> public async Task Invoke(HttpContext httpContext) { if (!_options.Disabled && _options.TryMatch(httpContext, out var ipSafeList)) { var remoteIp = httpContext.Connection.RemoteIpAddress; _logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp); var bytes = remoteIp.GetAddressBytes(); var badIp = true; foreach (var address in ipSafeList) { if (address.SequenceEqual(bytes)) { badIp = false; break; } } if (badIp) { _logger.LogWarning( "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp); httpContext.Response.StatusCode = (int)_options.HttpStatusCode; return; } } await _next?.Invoke(httpContext); }
public async Task Invoke(HttpContext httpContext) { _logger.LogInformation($"Started: {httpContext.Request.Path}"); await _next?.Invoke(httpContext); _logger.LogInformation($"Finnished: {httpContext.Request.Path}"); }
public async Task Invoke(HttpContext context) { if (context.WebSockets.IsWebSocketRequest) { var currentSocket = await context.WebSockets.AcceptWebSocketAsync(); string json = await RecieveStringAsync(currentSocket, context.RequestAborted); var data = JsonConvert.DeserializeObject <dynamic>(json); switch (data.Operation.ToString()) { case "CheckEmailConfirmationStatus": await ProcessEmailConfirmation(context, currentSocket, context.RequestAborted, data.Parameters.ToString()); break; } } if (context.Request.Path.Equals("/Registration/CheckEmailConfirmationStatus")) { await ProcessEmailConfirmation(context); } else { await next?.Invoke(context); } }
public async Task InvokeAsync(HttpContext context) { if (context is null) { throw new ArgumentNullException(nameof(context)); } var(useDefaultPolicy, policyName) = options is null ? (true, null) : (options.UseDefault, options.PolicyName); var policy = await(useDefaultPolicy ? policyProvider.GetDefaultPolicyAsync() : policyProvider.GetPolicyAsync(policyName)); // Policy evaluator has transient lifetime so it fetched from request services instead of injecting in constructor var policyEvaluator = context.RequestServices.GetRequiredService <IPolicyEvaluator>(); var authenticateResult = await policyEvaluator.AuthenticateAsync(policy, context); var authorizeResult = await policyEvaluator.AuthorizeAsync(policy, authenticateResult, context, resource : null); if (authorizeResult.Challenged) { if (policy.AuthenticationSchemes.Any()) { foreach (var scheme in policy.AuthenticationSchemes) { await context.ChallengeAsync(scheme); } } else { await context.ChallengeAsync(); } return; } else if (authorizeResult.Forbidden) { if (policy.AuthenticationSchemes.Any()) { foreach (var scheme in policy.AuthenticationSchemes) { await context.ForbidAsync(scheme); } } else { await context.ForbidAsync(); } return; } await(next?.Invoke(context) ?? Task.CompletedTask); }
public Task InvokeAsync(TestContext context, RequestDelegate <TestContext> next) { context.N++; if (context.N != 5) { throw new TestException(); } return(next?.Invoke(context)); }
public async Task Invoke(HttpContext context) { if (!context.Items.ContainsKey(Constants.HttpContextTenantKey)) { var tenantService = context.RequestServices.GetService(typeof(TenantAccessService <T>)) as TenantAccessService <T>; context.Items.Add(Constants.HttpContextTenantKey, await tenantService.GetTenantAsync()); } // Continue processing await next?.Invoke(context); }
public async Task Invoke(HttpContext context) { if (context.Request.Path.Equals("/CheckEmailConfirmationStatus")) { await ProcessEmailConfirmation(context); } else { await _next?.Invoke(context); } }
public async Task Invoke(HttpContext context) { try { await _requestDelegate?.Invoke(context); } catch (Exception ex) { await HandleException(context, ex); } }
public async Task Dispatch(HttpContext context, LayIMOptions options, RequestDelegate next) { if (context.IsLayIMResourceRequest(options)) { await next?.Invoke(context); } else { context.Response.StatusCode = StatusCodes.Status404NotFound; } }
public async Task InvokeAsync(HttpContext context) { var path = context.Request.Path.Value; if (!path.StartsWith($"/{_apiPrefix}", System.StringComparison.Ordinal) && !Path.HasExtension(path)) { context.Request.Path = _filename; } await(_next?.Invoke(context) ?? Task.CompletedTask); }
public Task Invoke(HttpContext context) { if (string.IsNullOrWhiteSpace(header)) { context.Response.Headers.Remove(Constants.ServerHeader); } else { context.Response.Headers[Constants.ServerHeader] = header; } return(_next?.Invoke(context)); }
public async Task InvokeAsync(HttpContext context) { if (context.Request.Query.ContainsKey("token") && context.Request.Query["token"] == "12345") { context.Items["message"] = _message; await _next?.Invoke(context); } else { context.Response.StatusCode = 403; } }
public Task Invoke(HttpContext context) { if (options.guard.HasValue) { context.Response.Headers[Constants.FrameGuardHeader] = Enum.GetName(typeof(FrameGuardOptions.FrameGuard), options.guard); } else if (!string.IsNullOrWhiteSpace(options.domain)) { context.Response.Headers[Constants.FrameGuardHeader] = options.domain; } return(next?.Invoke(context)); }
public async Task Invoke(HttpContext context) { var path = context.Request.Path; var method = context.Request.Method; _counter.Labels(path, method).Inc(); var stopwatch = System.Diagnostics.Stopwatch.StartNew(); await _next?.Invoke(context); var elapsed = stopwatch.Elapsed.TotalMilliseconds * 1000; _requestDuration.Labels(path, method).Observe(elapsed); }
public async Task Invoke(HttpContext context) { if (context.WebSockets.IsWebSocketRequest) { if (_diagnosticSource.IsEnabled("TicTacToe.MiddlewareStarting")) { _diagnosticSource.Write("TicTacToe.MiddlewareStarting", new { httpContext = context }); } var webSocket = await context.WebSockets.AcceptWebSocketAsync(); var ct = context.RequestAborted; var json = await ReceiveStringAsync(webSocket, ct); var command = JsonConvert.DeserializeObject <dynamic>(json); switch (command.Operation.ToString()) { case "CheckEmailConfirmationStatus": { await ProcessEmailConfirmation(context, webSocket, ct, command.Parameters.ToString()); break; } case "CheckGameInvitationConfirmationStatus": { await ProcessGameInvitationConfirmation(context, webSocket, ct, command.Parameters.ToString()); break; } } } else if (context.Request.Path.Equals("/CheckEmailConfirmationStatus")) { await ProcessEmailConfirmation(context); } else if (context.Request.Path.Equals("/CheckGameInvitationConfirmationStatus")) { await ProcessGameInvitationConfirmation(context); } else { await _next?.Invoke(context); } }
public async Task Invoke(HttpContext context, RequestServicesSwapper <TTenant> requestServicesSwapper, ITenantContainerAccessor <TTenant> tenantContainerAccessor, ITenantRequestContainerAccessor <TTenant> requestContainerAccessor) { _logger.LogDebug("Tenant Container Middleware - Start."); var tenantContainer = await tenantContainerAccessor.TenantContainer.Value; if (tenantContainer == null) { _logger.LogDebug("Tenant Container Middleware - No tenant container."); await _next.Invoke(context); return; } var oldAppBuilderServices = _appBuilder.ApplicationServices; try { // Can't remember why this is necessary to swap appBuilder.ApplicationServices here.. might be some mvc thing, need to rediscover. _logger.LogDebug("Setting AppBuilder Services to Tenant Container: {containerId} - {containerName}", tenantContainer.ContainerId, tenantContainer.ContainerName); _appBuilder.ApplicationServices = tenantContainer; var perRequestContainer = await requestContainerAccessor.TenantRequestContainer.Value; // Ensure per request container is disposed at end of request. context.Response.RegisterForDispose(perRequestContainer); // Replace request services with a nested version (for lifetime management - used to encpasulate a request). _logger.LogDebug("Setting Request Container: {containerId} - {containerName}", perRequestContainer.ContainerId, perRequestContainer.ContainerName); requestServicesSwapper.SwapRequestServices(perRequestContainer); // var swapContextRequestServices = new RequestServicesSwapper(perRequestContainer); // swapContextRequestServices.SwapRequestServices() await _next?.Invoke(context); //await swapContextRequestServices.ExecuteWithinSwappedRequestContainer(_next, context); _logger.LogDebug("Restoring Request Container"); } catch (Exception ex) { _logger.LogWarning(ex.Message); } finally { _logger.LogDebug("Restoring AppBuilder Services"); _appBuilder.ApplicationServices = oldAppBuilderServices; } }
/// <summary> /// Invokes the asynchronous. /// </summary> /// <param name="httpContext">The HTTP context.</param> public async Task InvokeAsync(HttpContext httpContext) { try { if (httpContext != null) { await(_requestDelegate?.Invoke(httpContext)).ConfigureAwait(false); } } catch (Exception ex) { await HandleExceptionAsync(httpContext, ex).ConfigureAwait(false); } }
public async Task InvokeAsync(HttpContext contex) { await _next?.Invoke(contex); int statuscode = contex.Response.StatusCode; if (statuscode == 404) { await contex.Response.WriteAsync("page not found"); } else if (statuscode == 403) { await contex.Response.WriteAsync("access denied"); } }
public async Task InvokeAsync(HttpContext context) { object ip = null; context.Items.TryGetValue("ClientIP", out ip); string queryString = $"{context.Request.Method} {context.Request.PathBase}/{context.Request.Path}?{context.Request.QueryString}"; logger.LogInformation("{QueryId}. Начало выполнения запроса {QueryString}. IP клиента: {ClientIP}", context.TraceIdentifier, queryString, ip); Exception e = null; Stopwatch sw = Stopwatch.StartNew(); try { await next?.Invoke(context); } catch (AggregateException ex) { e = ex.InnerException; } catch (Exception ex) { e = ex; } sw.Stop(); if (e != null) { logger.LogError(e, "{QueryId}. Ошибка выполнения запроса {QueryString}. IP клиента: {ClientIP}. {ErrorMsg}", context.TraceIdentifier, queryString, ip, e.Message); throw e; } var level = sw.ElapsedMilliseconds >= kWarnPeriod ? LogLevel.Warning : LogLevel.Information; logger.Log(level, "{QueryId}. Окончание выполнения запроса {QueryString}. IP клиента: {ClientIP}. Период: {Period}", context.TraceIdentifier, queryString, ip, sw.ElapsedMilliseconds); }
public Task Invoke(HttpContext context) { var result = Constants.OneModeEqualsBlock; var userAgent = context.Request.Headers[Constants.UserAgent]; if (!addOldIE && !string.IsNullOrWhiteSpace(userAgent)) { var matches = ieMatch.Match(userAgent); int version; if (matches.Success && int.TryParse(matches?.Groups[2]?.Value, out version) && (version == 7 || version == 8 || version == 9)) { result = Constants.Zero; } } context.Response.Headers[Constants.XXSProtection] = result; return(_next?.Invoke(context)); }
public async Task Invoke(HttpContext contexto) { if (contexto.WebSockets.IsWebSocketRequest) { // Es una solicitud por websocket, recibir el json recibido var webSocket = await contexto.WebSockets.AcceptWebSocketAsync(); var tokenCancelacion = contexto.RequestAborted; var json = await RecibirStringAsync(webSocket, tokenCancelacion); var comando = JsonConvert.DeserializeObject <dynamic>(json); switch (comando.Operation.ToString()) { case "ChequearEstadoConfirmacionEmail": { // Procesar la confirmación del mail usando websocket // por medio de websocket tan pronto como sea posible await ProcesarConfirmacionEmail(contexto, webSocket, tokenCancelacion, comando.Parameters.ToString()); break; } case "ChequearEstadoInvitacionJuego": { await ProcesarConfirmacionInvitacionJuego(contexto, webSocket, tokenCancelacion, comando.Parameters.ToString()); break; } } } else if (contexto.Request.Path.Equals("/ChequearEstadoConfirmacionEmail")) { await ProcesarConfirmacionEmail(contexto); } else if (contexto.Request.Path.Equals("/ChequearConfirmacionEstadoInvitacionJuego")) { await ProcesarConfirmacionInvitacionJuego(contexto); } else { await _siguiente?.Invoke(contexto); } }
/// <summary> /// Gets called by ASP.NET framework /// </summary> /// <param name="context">Instance of <see cref="HttpContext"/> provided by ASP.NET framework</param> /// <returns></returns> public async Task Invoke(HttpContext context) { ILogger log = new ContextAwareLogger(_isLoggingEnabled, _logger, context.TraceIdentifier); log.LogInformation($"Received request: {context.Request.Path} with query: {context.Request.QueryString.ToString() ?? ""}"); IPathResolver pathResolver = Options.InternalServiceResolver.GetPathResolver(); ActionContext action = pathResolver.ResolveAction(context.Request, log); if (action == null) { log.LogInformation("Request is skipped to next middleware"); if (_next != null) { log.LogInformation("Invoking next middleware"); await _next?.Invoke(context); log.LogInformation("Next middleware invoked"); } else { log.LogInformation("There is no next middleware to invoke"); } } else { if (Options.RequiresHttps && !context.Request.IsHttps) { log.LogInformation("LiteApi options are set to require HTTPS, request rejected because request is HTTP"); context.Response.StatusCode = 400; await context.Response.WriteAsync("Bad request, HTTPS request was expected."); } else { var actionInvoker = Options.InternalServiceResolver.GetActionInvoker(); await actionInvoker.Invoke(context, action, log); log.LogInformation("Action is invoked"); } } log.LogInformation("Request is processed"); }
/// <summary> /// Invokes the middleware. /// </summary> /// <param name="context"></param> /// <param name="next"></param> /// <returns></returns> public async Task InvokeAsync(HttpContext context) { if (host.State == CommunicationState.Created) { await host.OpenAsync(); await Task.Delay(TimeSpan.FromSeconds(1)); } if (host.State != CommunicationState.Opened) { throw new CommunicationException("ServiceHost is not open. Cannot route request."); } // dispatch request to router, which sends to service host context.Items[AspNetCoreUri.UriContextItemName] = new Uri(baseUri, context.Request.Path.Value?.TrimStart('/') ?? PathString.Empty); await router.RunAsync(context); // continue with pipe await next?.Invoke(context); }
public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { _logger.StartingProcessingRequest(new { context.Request.Path, context.Request.PathBase }); await next?.Invoke(context); _logger.SuccessfullyProcessedRequest(new { context.Request.Path, context.Request.PathBase }); } catch (Exception ex) { _logger.FailedProcessingRequest(ex, ex.Message, new { context.Request.Path }); if (_exceptionHandler != null) { _exceptionHandler.Handle(context, ex); } else { throw; } } }
public async Task Invoke(HttpContext context) { if (context.IsLayIMRequest(options) == false) { await next?.Invoke(context); return; } string path = context.ToRoutePath(options); var dispatcher = LayIMRoutes.Routes.FindDispatcher(path); if (dispatcher != null) { await dispatcher.Dispatch(context); } else { await LayIMRoutes.ResourceDispatcher.Dispatch(context, options, next); } }
public async Task Invoke(HttpContext context) { var typed = context.Request.GetTypedHeaders(); string value = context.Request.Headers["Authorization"]; var values = value.Split(":"); var date = typed.Date.Value.UtcDateTime; var keyId = values[0].Replace("Authorization ", ""); var signature = values[1]; var message = Secret.BuildMessage(date, AuthenticateUri); var computeSignature = Hmacsha1.ComputeSignature(Secret.GetSecretKey(keyId), message); var result = signature.Equals(computeSignature); if (!result) { context.Abort(); } await _next?.Invoke(context); }
public async Task Invoke(HttpContext context) { if (IsSwagger(context)) { await _next(context); return; } var actualResponseStream = context.Response.Body; try { using (var responseStream = new MemoryStream()) { context.Response.Body = responseStream; await _next.Invoke(context); string bodyString = ""; switch (context.Response.StatusCode) { case (int)HttpStatusCode.OK: bodyString = await _GetOkResponse(context); // need to write back break; case (int)HttpStatusCode.Unauthorized: bodyString = _GetUnauthorizedResponse(context); break; default: bodyString = _GetDefaultResponse(context); break; } // replace stream, context.Response.Body = new MemoryStream(); // write final response to stream await context.Response.WriteAsync(bodyString); // reset stream, so client can read stream context.Response.Body.Seek(0, SeekOrigin.Begin); // copy back to the actual stream await context.Response.Body.CopyToAsync(actualResponseStream); } } catch (Exception ex) { // Replace with original stream if an error occurs context.Response.Body = actualResponseStream; // rethrow the exception throw ex; } }
public async Task Invoke(HttpContext context) { // check if rate limiting is enabled if (_options == null) { await _next.Invoke(context); return; } // compute identity from request var identity = await ResolveIdentityAsync(context); // check white list if (_processor.IsWhitelisted(identity)) { await _next.Invoke(context); return; } var rules = await _processor.GetMatchingRulesAsync(identity, context.RequestAborted); var rulesDict = new Dictionary <RateLimitRule, RateLimitCounter>(); foreach (var rule in rules) { // increment counter var rateLimitCounter = await _processor.ProcessRequestAsync(identity, rule, context.RequestAborted); if (rule.Limit > 0) { // check if key expired if (rateLimitCounter.Timestamp + rule.PeriodTimespan.Value < DateTime.UtcNow) { continue; } // check if limit is reached if (rateLimitCounter.Count > rule.Limit) { //compute retry after value var retryAfter = rateLimitCounter.Timestamp.RetryAfterFrom(rule); // log blocked request LogBlockedRequest(context, identity, rateLimitCounter, rule); if (_options.RequestBlockedBehaviorAsync != null) { await _options.RequestBlockedBehaviorAsync(context, identity, rateLimitCounter, rule); } if (!rule.MonitorMode) { // break execution await ReturnQuotaExceededResponse(context, rule, retryAfter); return; } } } // if limit is zero or less, block the request. else { // log blocked request LogBlockedRequest(context, identity, rateLimitCounter, rule); if (_options.RequestBlockedBehaviorAsync != null) { await _options.RequestBlockedBehaviorAsync(context, identity, rateLimitCounter, rule); } if (!rule.MonitorMode) { // break execution (Int32 max used to represent infinity) await ReturnQuotaExceededResponse(context, rule, int.MaxValue.ToString(System.Globalization.CultureInfo.InvariantCulture)); return; } } rulesDict.Add(rule, rateLimitCounter); } // set X-Rate-Limit headers for the longest period if (rulesDict.Any() && !_options.DisableRateLimitHeaders) { var rule = rulesDict.OrderByDescending(x => x.Key.PeriodTimespan).FirstOrDefault(); var headers = _processor.GetRateLimitHeaders(rule.Value, rule.Key, context.RequestAborted); headers.Context = context; context.Response.OnStarting(SetRateLimitHeaders, state: headers); } await _next.Invoke(context); }
private async Task Invoke(RequestDelegate next, HttpContext content) { Console.WriteLine("初始化组件开始"); await next.Invoke(content); Console.WriteLine("管道下步执行完毕"); }