private protected override void InternalPostCreateContext( HostingApplication.Context context, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext) { var authorizer = apiGatewayRequest?.RequestContext?.Authorizer; if (authorizer != null) { // handling claims output from cognito user pool authorizer if (authorizer.Claims != null && authorizer.Claims.Count != 0) { var identity = new ClaimsIdentity(authorizer.Claims.Select( entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); lambdaContext.Logger.LogLine( $"Configuring HttpContext.User with {authorizer.Claims.Count} claims coming from API Gateway's Request Context"); context.HttpContext.User = new ClaimsPrincipal(identity); } else { // handling claims output from custom lambda authorizer var identity = new ClaimsIdentity( authorizer.Where(x => !string.Equals(x.Key, "claims", StringComparison.OrdinalIgnoreCase)) .Select(entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); lambdaContext.Logger.LogLine( $"Configuring HttpContext.User with {authorizer.Count} claims coming from API Gateway's Request Context"); context.HttpContext.User = new ClaimsPrincipal(identity); } } }
/// <summary> /// Start processing the request. /// </summary> /// <returns></returns> internal Task <HttpContext> SendAsync(CancellationToken cancellationToken) { var registration = cancellationToken.Register(AbortRequest); _testContext = _application.CreateContext(_httpContext.Features); // Async offload, don't let the test code block the caller. _ = Task.Factory.StartNew(async() => { try { await _application.ProcessRequestAsync(_testContext); await CompleteResponseAsync(); _application.DisposeContext(_testContext, exception: null); } catch (Exception ex) { Abort(ex); _application.DisposeContext(_testContext, ex); } finally { registration.Dispose(); } }); return(_responseTcs.Task); }
public void HttpRequestIn_PopulateSpan() { var tracer = GetTracer(); IObserver <KeyValuePair <string, object> > observer = new AspNetCoreDiagnosticObserver(tracer); var context = new HostingApplication.Context { HttpContext = GetHttpContext() }; observer.OnNext(new KeyValuePair <string, object>("Microsoft.AspNetCore.Hosting.HttpRequestIn.Start", context)); var scope = tracer.ActiveScope; Assert.NotNull(scope); var span = scope.Span; Assert.NotNull(span); Assert.Equal("aspnet_core.request", span.OperationName); Assert.Equal("aspnet_core", span.GetTag(Tags.InstrumentationName)); Assert.Equal(SpanTypes.Web, span.Type); Assert.Equal("GET /home/?/action", span.ResourceName); Assert.Equal(SpanKinds.Server, span.GetTag(Tags.SpanKind)); Assert.Equal("GET", span.GetTag(Tags.HttpMethod)); Assert.Equal("localhost", span.GetTag(Tags.HttpRequestHeadersHost)); Assert.Equal("http://localhost/home/1/action", span.GetTag(Tags.HttpUrl)); Assert.Equal(TracerConstants.Language, span.GetTag(Tags.Language)); }
protected async Task <APIGatewayProxyResponse> MyProcessRequest(ILambdaContext lambdaContext, HostingApplication.Context context, InvokeFeatures features, bool rethrowUnhandledError = false) { _logger.LogInformation("MY PROCESS REQUEST!!!"); var resp = await base.ProcessRequest(lambdaContext, context, features, rethrowUnhandledError); if (resp.Body != null && resp.Headers.ContainsKey("Content-Type")) { if ("application/octet-stream" == resp.Headers["Content-Type"]) { _logger.LogInformation("SETTING B64!!!"); resp = new MyAPIGatewayProxyResponse { Body = resp.Body, Headers = resp.Headers, StatusCode = resp.StatusCode, IsBase64Encoded = true, }; } } return(resp); }
public static void ContextDisposed(HostingApplication.Context context) { if (context.EventLogEnabled) { // Non-inline HostingEventSource.Log.RequestStop(); } }
public void BeginRequest(HttpContext httpContext, HostingApplication.Context context) { if (httpContext.Request.Headers.ContainsKey(CorrelationVectorPropagationDelegates.HeaderName)) { httpContext.SetCorrelationVector( CorrelationVector.Extend(httpContext.Request.Headers[CorrelationVectorPropagationDelegates.HeaderName][0])); } }
public void BeginRequest(HttpContext httpContext, HostingApplication.Context context) { var currentExtension = context.Activity?.GetActivityExtension <CorrelationVectorExtension>(); if (currentExtension != null && httpContext.Request.Headers.ContainsKey(CorrelationVectorPropagationDelegates.HeaderName)) { currentExtension.SetExternalCorrelationVectorParent( httpContext.Request.Headers[CorrelationVectorPropagationDelegates.HeaderName][0]); } }
private protected override void InternalPostCreateContext(HostingApplication.Context context, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext) { if (apiGatewayRequest?.RequestContext?.Authorizer?.Claims != null) { var identity = new ClaimsIdentity(apiGatewayRequest.RequestContext.Authorizer.Claims.Select( entry => new Claim(entry.Key, entry.Value.ToString())), "AuthorizerIdentity"); _logger.LogDebug($"Configuring HttpContext.User with {apiGatewayRequest.RequestContext.Authorizer.Claims.Count} claims coming from API Gateway's Request Context"); context.HttpContext.User = new ClaimsPrincipal(identity); } }
private void LogRequestStarting(HostingApplication.Context context) { // IsEnabled is checked in the caller, so if we are here just log var startLog = new HostingRequestStartingLog(context.HttpContext !); context.StartLog = startLog; _logger.Log( logLevel: LogLevel.Information, eventId: LoggerEventIds.RequestStarting, state: startLog, exception: null, formatter: HostingRequestStartingLog.Callback); }
private protected override void InternalCustomResponseExceptionHandling(HostingApplication.Context context, ApplicationLoadBalancerResponse lambdaResponse, ILambdaContext lambdaContext, Exception ex) { var errorName = ex.GetType().Name; if (this._multiHeaderValuesEnabled) { lambdaResponse.MultiValueHeaders.Add(new KeyValuePair <string, IList <string> >("ErrorType", new List <string> { errorName })); } else { lambdaResponse.Headers.Add(new KeyValuePair <string, string>("ErrorType", errorName)); } }
private void LogRequestFinished(HostingApplication.Context context, long startTimestamp, long currentTimestamp) { // IsEnabled isn't checked in the caller, startTimestamp > 0 is used as a fast proxy check // but that may be because diagnostics are enabled, which also uses startTimestamp, // so check if we logged the start event if (context.StartLog != null) { var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp))); _logger.Log( logLevel: LogLevel.Information, eventId: LoggerEventIds.RequestFinished, state: new HostingRequestFinishedLog(context, elapsed), exception: null, formatter: HostingRequestFinishedLog.Callback); } }
public void HttpRequestIn_FilterRequest() { var tracer = GetTracer(); var httpContext = GetHttpContext(); var options = new AspNetCoreDiagnosticOptions(); options.IgnorePatterns.Add(h => object.ReferenceEquals(h, httpContext)); IObserver <KeyValuePair <string, object> > observer = new AspNetCoreDiagnosticObserver(tracer, options); var context = new HostingApplication.Context { HttpContext = httpContext }; observer.OnNext(new KeyValuePair <string, object>("Microsoft.AspNetCore.Hosting.HttpRequestIn.Start", context)); var scope = tracer.ActiveScope; Assert.Null(scope); }
public DateRepository(HostingApplication.Context testTaskCtx) { _testTaskCtx = testTaskCtx; }
/// <summary> /// This method is called after the HostingApplication.Context has been created. Derived classes can overwrite this method to alter /// the context before passing the request to ASP.NET Core to process the request. /// </summary> /// <param name="context">Context.</param> /// <param name="request">Request.</param> /// <param name="fcContext">Fc context.</param> protected virtual void PostCreateContext(HostingApplication.Context context, HttpRequest request, IFcContext fcContext) { }
/// <summary> /// Processes the current request. /// </summary> /// <param name="lambdaContext"><see cref="ILambdaContext"/> implementation.</param> /// <param name="context">The hosting application request context object.</param> /// <param name="features">An <see cref="InvokeFeatures"/> instance.</param> /// <param name="rethrowUnhandledError"> /// If specified, an unhandled exception will be rethrown for custom error handling. /// Ensure that the error handling code calls 'this.MarshallResponse(features, 500);' after handling the error to return a <see cref="APIGatewayProxyResponse"/> to the user. /// </param> protected async Task <APIGatewayProxyResponse> ProcessRequest(ILambdaContext lambdaContext, HostingApplication.Context context, InvokeFeatures features, bool rethrowUnhandledError = false) { var defaultStatusCode = 200; Exception ex = null; try { await this._server.Application.ProcessRequestAsync(context); } catch (AggregateException agex) { ex = agex; lambdaContext.Logger.LogLine($"Caught AggregateException: '{agex}'"); var sb = new StringBuilder(); foreach (var newEx in agex.InnerExceptions) { sb.AppendLine(this.ErrorReport(newEx)); } lambdaContext.Logger.LogLine(sb.ToString()); defaultStatusCode = 500; } catch (ReflectionTypeLoadException rex) { ex = rex; lambdaContext.Logger.LogLine($"Caught ReflectionTypeLoadException: '{rex}'"); var sb = new StringBuilder(); foreach (var loaderException in rex.LoaderExceptions) { var fileNotFoundException = loaderException as FileNotFoundException; if (fileNotFoundException != null && !string.IsNullOrEmpty(fileNotFoundException.FileName)) { sb.AppendLine($"Missing file: {fileNotFoundException.FileName}"); } else { sb.AppendLine(this.ErrorReport(loaderException)); } } lambdaContext.Logger.LogLine(sb.ToString()); defaultStatusCode = 500; } catch (Exception e) { ex = e; if (rethrowUnhandledError) { throw; } lambdaContext.Logger.LogLine($"Unknown error responding to request: {this.ErrorReport(e)}"); defaultStatusCode = 500; } finally { this._server.Application.DisposeContext(context, ex); } if (features.ResponseStartingEvents != null) { await features.ResponseStartingEvents.ExecuteAsync(); } var response = this.MarshallResponse(features, lambdaContext, defaultStatusCode); lambdaContext.Logger.LogLine($"Response Base 64 Encoded: {response.IsBase64Encoded}"); if (ex != null) { response.Headers.Add(new KeyValuePair <string, string>("ErrorType", ex.GetType().Name)); } if (features.ResponseCompletedEvents != null) { await features.ResponseCompletedEvents.ExecuteAsync(); } return(response); }
/// <summary> /// This method is called after the HostingApplication.Context has been created. Derived classes can overwrite this method to alter /// the context before passing the request to ASP.NET Core to process the request. /// </summary> /// <param name="context"></param> /// <param name="apiGatewayRequest"></param> /// <param name="lambdaContext"></param> protected virtual void PostCreateContext(HostingApplication.Context context, APIGatewayProxyRequest apiGatewayRequest, ILambdaContext lambdaContext) { }
public void BeginRequest(HttpContext httpContext, HostingApplication.Context context) { long startTimestamp = 0; if (HostingEventSource.Log.IsEnabled()) { context.EventLogEnabled = true; // To keep the hot path short we defer logging in this function to non-inlines RecordRequestStartEventLog(httpContext); } var diagnosticListenerEnabled = _diagnosticListener.IsEnabled(); var diagnosticListenerActivityCreationEnabled = (diagnosticListenerEnabled && _diagnosticListener.IsEnabled(ActivityName, httpContext)); var loggingEnabled = _logger.IsEnabled(LogLevel.Critical); if (loggingEnabled || diagnosticListenerActivityCreationEnabled || _activitySource.HasListeners()) { context.Activity = StartActivity(httpContext, loggingEnabled, diagnosticListenerActivityCreationEnabled, out var hasDiagnosticListener); context.HasDiagnosticListener = hasDiagnosticListener; if (context.Activity is Activity activity) { if (httpContext.Features.Get <IHttpActivityFeature>() is IHttpActivityFeature feature) { feature.Activity = activity; } else { httpContext.Features.Set(context.HttpActivityFeature); } } } if (diagnosticListenerEnabled) { if (_diagnosticListener.IsEnabled(DeprecatedDiagnosticsBeginRequestKey)) { startTimestamp = Stopwatch.GetTimestamp(); RecordBeginRequestDiagnostics(httpContext, startTimestamp); } } // To avoid allocation, return a null scope if the logger is not on at least to some degree. if (loggingEnabled) { // Scope may be relevant for a different level of logging, so we always create it // see: https://github.com/aspnet/Hosting/pull/944 // Scope can be null if logging is not on. context.Scope = Log.RequestScope(_logger, httpContext); if (_logger.IsEnabled(LogLevel.Information)) { if (startTimestamp == 0) { startTimestamp = Stopwatch.GetTimestamp(); } // Non-inline LogRequestStarting(context); } } context.StartTimestamp = startTimestamp; }
protected override void PostCreateContext(HostingApplication.Context context, APIGatewayProxyRequest lambdaRequest, ILambdaContext lambdaContext) { base.PostCreateContext(context, lambdaRequest, lambdaContext); AddNameClaim(context.HttpContext.User.Identity as ClaimsIdentity); }
private protected override void InternalCustomResponseExceptionHandling(HostingApplication.Context context, APIGatewayProxyResponse apiGatewayResponse, ILambdaContext lambdaContext, Exception ex) { apiGatewayResponse.MultiValueHeaders["ErrorType"] = new List <string> { ex.GetType().Name }; }
/// <summary> /// Processes the current request. /// </summary> /// <param name="fcContext"><see cref="IFcContext"/> implementation.</param> /// <param name="context">The hosting application request context object.</param> /// <param name="features">An <see cref="InvokeFeatures"/> instance.</param> /// <param name="rethrowUnhandledError"> /// If specified, an unhandled exception will be rethrown for custom error handling. /// Ensure that the error handling code calls 'this.MarshallResponse(features, 500);' after handling the error to return a <see cref="HttpResponse"/> to the user. /// </param> protected async Task <HttpResponse> ProcessRequest(IFcContext fcContext, HostingApplication.Context context, InvokeFeatures features, HttpResponse response, bool rethrowUnhandledError = false) { var defaultStatusCode = 200; Exception ex = null; try { await this._server.Application.ProcessRequestAsync(context); } catch (AggregateException agex) { ex = agex; Logger.LogError($"Caught AggregateException: '{agex}'"); var sb = new StringBuilder(); foreach (var newEx in agex.InnerExceptions) { sb.AppendLine(this.ErrorReport(newEx)); } Logger.LogError(sb.ToString()); defaultStatusCode = 500; } catch (ReflectionTypeLoadException rex) { ex = rex; Logger.LogError($"Caught ReflectionTypeLoadException: '{rex}'"); var sb = new StringBuilder(); foreach (var loaderException in rex.LoaderExceptions) { var fileNotFoundException = loaderException as FileNotFoundException; if (fileNotFoundException != null && !string.IsNullOrEmpty(fileNotFoundException.FileName)) { sb.AppendLine($"Missing file: {fileNotFoundException.FileName}"); } else { sb.AppendLine(this.ErrorReport(loaderException)); } } Logger.LogError(sb.ToString()); defaultStatusCode = 500; } catch (Exception e) { ex = e; if (rethrowUnhandledError) { throw; } Logger.LogError($"Unknown error responding to request: {this.ErrorReport(e)}"); defaultStatusCode = 500; } finally { this._server.Application.DisposeContext(context, ex); } if (features.ResponseStartingEvents != null) { await features.ResponseStartingEvents.ExecuteAsync(); } this.MarshallResponse(features, fcContext, response, defaultStatusCode); if (features.ResponseCompletedEvents != null) { await features.ResponseCompletedEvents.ExecuteAsync(); } return(response); }
public void RequestEnd(HttpContext httpContext, Exception?exception, HostingApplication.Context context) { // Local cache items resolved multiple items, in order of use so they are primed in cpu pipeline when used var startTimestamp = context.StartTimestamp; long currentTimestamp = 0; // If startTimestamp was 0, then Information logging wasn't enabled at for this request (and calculated time will be wildly wrong) // Is used as proxy to reduce calls to virtual: _logger.IsEnabled(LogLevel.Information) if (startTimestamp != 0) { currentTimestamp = Stopwatch.GetTimestamp(); // Non-inline LogRequestFinished(context, startTimestamp, currentTimestamp); } if (_diagnosticListener.IsEnabled()) { if (currentTimestamp == 0) { currentTimestamp = Stopwatch.GetTimestamp(); } if (exception == null) { // No exception was thrown, request was successful if (_diagnosticListener.IsEnabled(DeprecatedDiagnosticsEndRequestKey)) { // Diagnostics is enabled for EndRequest, but it may not be for BeginRequest // so call GetTimestamp if currentTimestamp is zero (from above) RecordEndRequestDiagnostics(httpContext, currentTimestamp); } } else { // Exception was thrown from request if (_diagnosticListener.IsEnabled(DiagnosticsUnhandledExceptionKey)) { // Diagnostics is enabled for UnhandledException, but it may not be for BeginRequest // so call GetTimestamp if currentTimestamp is zero (from above) RecordUnhandledExceptionDiagnostics(httpContext, currentTimestamp, exception); } } } var activity = context.Activity; // Always stop activity if it was started if (activity is not null) { StopActivity(httpContext, activity, context.HasDiagnosticListener); } if (context.EventLogEnabled) { if (exception != null) { // Non-inline HostingEventSource.Log.UnhandledException(); } // Count 500 as failed requests if (httpContext.Response.StatusCode >= 500) { HostingEventSource.Log.RequestFailed(); } } // Logging Scope is finshed with context.Scope?.Dispose(); }